如何从$ cookie获取对象?
我在一个Cookie上存储一个用户对象,当客户再次访问这个站点时,我想使用这个对象的属性。
但是,当客户端回来,我的cookie对象看起来像[object object]
而它的属性看起来像undefined
。
这是我的代码:
$scope.signup = function (user) { $http.post('/api/signup', user) .then( function (res) { $cookies.put('user', res.data.user); //This is where I store my cookie. }, function (res) { }); };
当客户端回来时,我有这样的代码:
var lastUser = $cookies.get('user'); if (lastUser) $scope.lastName = lastUser.username; console.log(lastUser); // [object object] console.log(lastName); // undefined
我能做些什么来正确获取cookie信息?
改为:
window.localStorage.setItem('user', JSON.stringify(res.data.user));
然后,您可以通过以下方式获取相关信息:
var userData = JSON.parse(window.localStorage.getItem('user'));
这样你会避免很多的cookie头痛。