简体   繁体   English

AngularJS $ cookies.get()始终返回undefined

[英]AngularJS $cookies.get() always returns undefined

I'm using AngularJS 1.4.0 and the $cookies service. 我正在使用AngularJS 1.4.0和$cookies服务。 The following code will always print out an empty object: 以下代码将始终打印出一个空对象:

(function() {
    var app = angular.module("user-cookies-service", []);

    app.service('UserCookiesService', ["$cookies", function($cookies) {
        $cookies.put("Hello", "World");
        console.log($cookies.getAll());
    }]);
})();

I've tried: 我试过了:

  • Using AngulerJS 1.3.15 and $cookieStore where cookies don't persist when the browser is refreshed (but it at least created the cookies). 使用AngulerJS 1.3.15和$cookieStore ,刷新浏览器时cookie不会保留(但它至少创建了cookie)。
  • Adding an expiry date. 添加到期日。
  • Making sure Cookies are enabled in my browser (Chrome). 确保在我的浏览器(Chrome)中启用了Cookie。
  • Trying plain old JS, which still doesn't work. 尝试普通的旧JS,仍然无法正常工作。

I haven't been able to find a similar issue anywhere. 我无法在任何地方找到类似的问题。

Thank you. 谢谢。

A little late but for anyone having the same issue. 有点晚,但对于有同样问题的人。 I had a similar problem. 我遇到了类似的问题。 You have to make sure you are passing the correct options as the third parameter. 您必须确保将正确的选项作为第三个参数传递。 In my case the path was not being set. 在我的情况下,路径没有设置。 Angular uses your <base> tag to set the path. Angular使用您的<base>标记来设置路径。 If that is not available for whatever reason, it will not set the cookie. 如果因任何原因无法使用,则不会设置cookie。

try this 试试这个

$cookies.put('secret', 'I cant tell you' {
   expires: new Date(date),
   path: '/'
});

For anyone who stumbles upon this problem... 对于任何偶然发现这个问题的人......

By default, Chrome doesn't allow cookies for local files. 默认情况下,Chrome不允许将Cookie用于本地文件。 You have to run it with the --enable-file-cookies flag. 您必须使用--enable-file-cookies标志运行它。

Make sure Chrome is closed and open the Windows Command Prompt/Terminal and run the following command: 确保Chrome已关闭并打开Windows命令提示符/终端并运行以下命令:

<path-to-chrome>/chrome.exe --enable-file-cookies

This will allow you to put/get cookies locally. 这将允许您在本地放置/获取cookie。

Cheers! 干杯!

maybe cookies should be available after refresh, try to log it in opposite way 也许cookie应该在刷新后可用,尝试以相反的方式记录它

console.log($cookies.getAll());
$cookies.put("Hello", "World");

first load: {}, second load: {"Hello": "World"} 第一次加载:{},第二次加载:{“Hello”:“World”}

in angular 1.3, use $cookies.Hello = "world"; 在角度1.3中,使用$ cookies.Hello =“world”; to set cookie 设置cookie

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM