Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

javascript - AngularJS $cookies.get() always returns undefined

I'm using AngularJS 1.4.0 and the $cookies service. 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).
  • Adding an expiry date.
  • Making sure Cookies are enabled in my browser (Chrome).
  • Trying plain old JS, which still doesn't work.

I haven't been able to find a similar issue anywhere.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. If that is not available for whatever reason, it will not set the cookie.

try this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...