【问题标题】:AngularJS $cookies are not persistingAngularJS $cookies 没有持久化
【发布时间】:2014-09-02 08:33:31
【问题描述】:

我有一个带有记住用户名功能的登录表单。他们所做的只是选中该框,然后通过以下方式保存 cookie:

$scope.toggleCookie = function()
{
    //-- $scope.remember is the model for the checkbox
    $cookieStore.put('remember', $scope.remember);
    if (!$scope.remember) $cookieStore.remove('email');
}

当用户返回登录页面时,我首先检查remember cookie:

$scope.remember = ($cookieStore.get('remember') == null || $cookieStore.get('remember') == false) ? false : true;

然后我检查email cookie中是否有值:

$scope.email = ($cookieStore.get('email') != null) ? $cookieStore.get('email') : '';

现在以上所有工作正常,我可以登录并检查它,注销,我可以在输入字段中看到我的用户名。如果我取消选中它,登录并注销,用户名就消失了。

我还可以在 chrome 开发工具的 resources->cookies 选项卡中看到这种情况。

我可以刷新页面,但用户名仍然存在。

我的问题是当我关闭 chrome 时,重新打开它,所有的 cookie 数据都消失了。为什么是这样?一开始我对 cookie 没有太多经验。

【问题讨论】:

    标签: javascript angularjs cookies


    【解决方案1】:

    在 Angular v1.4 中,您可以最终为 cookie 设置一些选项。这是一个非常简单的例子:

    var now = new $window.Date(),
        // this will set the expiration to 6 months
        exp = new $window.Date(now.getFullYear(), now.getMonth()+6, now.getDate());
    
    $cookies.put('yourCookie','blabla',{
      expires: exp
    });
    
    var cookie = $cookies.get('yourCookie');
    console.log(cookie); // logs 'blabla'
    

    如果您在运行此代码后检查您的 cookie,您将看到过期将正确设置为名为 yourCookie 的 cookie。

    作为第三个参数传递给上述put 函数的对象也允许其他选项,例如设置pathdomainsecure。查看the docs 了解概览。

    【讨论】:

      【解决方案2】:

      所以它似乎是导致问题的到期。从 AngularJS 1.2.19 开始,您无法通过 $cookie$cookieStore 设置过期日期。

      为了解决这个问题,我改用了本地存储。我使用这个模块可以轻松访问本地存储:https://github.com/grevory/angular-local-storage

      改变起来很轻松。我将$cookieStore.get('remember'); 更改为localStorageService.get('remember');,以便您可以看到它们共享方法名称。不是put,而是add

      【讨论】:

        【解决方案3】:

        要使 cookie 在浏览器会话中持久存在,应设置到期日期。不幸的是,angularjs $cookie 服务似乎不支持这一点。看到这个帖子:AngularJS - How to set expiration date for cookie in AngularJS

        【讨论】:

        • 我在发布这个帖子后看到了那个帖子,并认为这与它有关。我遇到了一个允许你设置过期的指令。我希望情况仍然不是这样。
        • 我想我可以用localStorage来做这个
        猜你喜欢
        • 2023-04-05
        • 2021-05-29
        • 2016-12-31
        • 2014-12-12
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多