kisor kisor - 5 months ago 18
AngularJS Question

how to access saved data in $localStorage in angularjs

i am working on MEAN app, after successful user login i want to save returned user data in localStorage in browser so that i can use it further, i am using ngStorage module. where i am able to save user data in browser's localstorage. here is my code in LoginController :

function loginController($http, $location, $rootScope,$localStorage){
var vm = this;
vm.signIn = signIn;

function signIn() {
$http({
url: '/login',
method: 'post',
data: vm.login
}).then(function(respond) {
if(respond.data){
$localStorage.userData = respond.data;
var info = $localStorage.userData;
$rootScope.userInfo = info;
$location.path('/dashboard/'+respond.data._id);
}else{
$location.path('/');
}


no when i access $rootScope in my another controller i can get value that is stored in $localStorage. even in my chrome browser i can see from inspect that data is stored in $localStorage. BUT when i refresh my page i can see there is still data in browser in localStorage but not in my $rootscope. my rootScope gets null data after page refreshing, i would really appreciate any suggestion on how to access those data and stored in rootScope.

Answer

retrieve user data from local-storage when app reloads

app.run(function($rootScope){
  if(localStorage['userData'])
  {
    $rootScope.userData = JSON.parse(localStorage.getItem('userData'));
  }
});
Comments