Angularjs: Why Page Refresh Destroy The Values Of $rootscope?
Solution 1:
AngularJS is a JavaScript framework, everything is stored in memory heap and the heap is starts when you open a page and it's destroyed after you close it. In this context, browser refresh is like closing and re-opening the page.
To keep the value after refresh, you should store it in a cookie, for this you use for example $cookies
or sessionStorage / localStorage as recommended by M K.
Solution 2:
I tried to store auth token using cookies following the article at Getting started with AngularJS and ASP.NET MVC - The long awaited Part Three. But the cookies is destroyed whenever I hit F5 or refresh the Chrome browser.
That article says ngCookies helps to deal with page refresh to maintain token for page refresh. And I had thought it did and I did not know ngCookies killed me. It was destroyed if page is refresh! after hours to research online I see this article helps me.
According to M K, I used localStorage (or sessionStorage) helped me to get rid of the headache of cookies. Using cookies to store authentication token or something else is a bad idea. I ran into that problem and I got lost (did not know the bug coming from "using cookies") as the above article mentioned/confirmed. So, it was a bug in that article.
Thank you million times, M K.
Solution 3:
Use localStorage and $stateChangerStart check if you using ui.route something like this
$rootScope.$on('$stateChangeStart', function(event, toState) {
// Grab the user from local storage and parse it to an objectvar user = JSON.parse(localStorage.getItem('user'));
if(user) {
$rootScope.currentUser = user;
}
});
Post a Comment for "Angularjs: Why Page Refresh Destroy The Values Of $rootscope?"