简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM