Ashok Vishwakarma
Ashok Vishwakarma

Reputation: 689

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.

Upvotes: 2

Views: 6112

Answers (2)

Juan Solano
Juan Solano

Reputation: 1200

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.

Upvotes: 3

Christoph
Christoph

Reputation: 27995

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.

Upvotes: -2

Related Questions