向 $cookies 添加 JSON 对象 - Angular JS

6
在控制台中,我的代码打印出:[Object, Object]。我无法正常地深入了解。
我尝试过JSON.Parse和JSON.stringify,但没有成功。
我的设置凭据的服务:
setCredentials.js
'use strict';

// service that handles setting and getting cookies  

app.service('setCredentials', function($cookies) {

    // function that gets json object and stores it inside a cookie
    this.storeInCookie = function(responseObject) {

        console.log(responseObject);

        //set the cookie
        var cookieObj = {
            currentUser: {
                userType: responseObject.auth.userType,
                username: responseObject.auth.email,
                token: responseObject.auth.token
            }
        };


        console.log(cookieObj);
        //set up header, in case we need auth token inside it for later 
        //$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
        //store inside of cookie
        $cookies.put('globals', cookieObj);

        return true;

    };

    //function to remove cookie
    this.removeCookie = function() {



    };

    //function to get cookie
    this.getCookie = function(cookieName) {

        //get cookie
        return $cookies.get(cookieName);

    };

});

我然后在控制器中调用 cookie 对象:
navigationController.js
'use strict';

//app global variable
//this is the controller that handles post requests
//declare services as dependecies $http, $location, custom service apiServiceWeb
app.controller('navigationController', function($scope, $rootScope, $http, $location, $cookies, setCredentials) {


  //navigation menu

  //get what is in the cookie
  var cookieValue = setCredentials.getCookie('globals');
  console.log($cookies.get('globals'));

});

请在你的服务声明中添加$log依赖项app.service('setCredentials', function($cookies, $log)...,然后你就可以使用高级日志记录功能,例如:$log.debug(responseObject);。希望这能帮到你。 - barfoos
1个回答

17
使用
$cookies.putObject('globals', cookieObj)

and
$cookies.getObject('globals')

相反。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接