How to store User Data in AngularJs
Can anyone please let me know how to store logged in user data into global scope of AngularJS,
My Login services is looked like this
App.service('Auth', function($http){
return {
isLogin:function(callback){
$http.get('api/auth/checkLogin').success(function(res){
callback(res);
});
},
login:function(user, callback){
$http.post('api/auth/login', user).success(function(res){
callback(res);
});
},
logout:function(callback){
$http.get('api/auth/logout').success(function(res){
callback(res);
});
}
};
});
I'm using the same in my controller like this
$scope.isLogin = false;
$scope.UserData = {};
$scope.login = function(user){
Auth.login(user, function(res){
if(res.status){
$scope.isLogin = true;
$scope.loginBoxShown = false;
$scope.UserData = res.data;
$location.path('/Dashboard');
}
});
};
Its working fine on first run but once I reload the page the variable $scope.isLogin
and $scope.UserData
are reset to their default value.
Is there any way to store them in a global scope permanently before my $scope.logout();
function delete them.
I normally use ngStorage for user data persistence. Found at https://github.com/gsklee/ngStorage
An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage.
Hope it helps.
The question isn't really Angular specific. To persist data across page reloads you basically have two options localStorage
(and it's little sister sessionStorage
) or cookies
.
Both techniques are covered in other SO answers already.
链接地址: http://www.djcxy.com/p/77826.html上一篇: AngularJS服务与工厂的优点和缺点
下一篇: 如何在AngularJs中存储用户数据