无法获得cookie值

时间:2015-12-02 15:06:09

标签: angularjs cookies

我不明白为什么我不能拿到我的饼干?

  

$ rootScopt.globals.currentUser = undefined

angular.module('MyModule', [
    'Authentication',
    'Home',
    'ngRoute',
    'ngCookies'
])
.config([
    //Config
])
.run([
    '$rootScope', '$location', '$cookies', '$http',
    function($rootScope, $location, $cookies, $http) {
        //Keep user logged in after page refresh
        $rootScope.globals = {
            currentUser: {
                username: "foo",
                password: "bar"
            }
        }

        $cookies.put('globals', $rootScope.globals);

        $rootScope.globals = $cookies.get('globals') || {};



        if ($rootScope.globals.currentUser) { //Never go in here..
            //Do stuff
        }
    }
]);

我已经检查过我的cookie存储了,它似乎工作正常。但是当我试图获取我的cookie时它不起作用。现在还有人为什么?

1 个答案:

答案 0 :(得分:1)

默认情况下,Chrome不允许使用Cookie作为本地文件。您必须使用--enable-file-cookies标志运行它。

尝试这种方式: jsfiddle

    angular.module('test',['ngCookies'])
  .run(function($rootScope, $cookies){
     $rootScope.globals = {
            currentUser: {
                username: "foo",
                password: "bar"
            }
        }
   $cookies.put('globals', JSON.stringify($rootScope.globals));
    var a = $cookies.get('globals');
    $rootScope.globals = JSON.parse(a) || {}
    console.log($rootScope.globals);
})