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.
gabrielAnzaldo
Updated on July 09, 2022Comments
-
gabrielAnzaldo almost 2 years
In my local route http://localhost:9000/#/deviceDetail/ I have a controller that manage that view. Before going to that view I set some variables to the
$rootScope
(for example$rootScope.dashboards
).Once on that view I have acces to dashboards property, but when I refresh the page with
F5
key for example the property dashboards is lost.I tried to save the
$rootScope
on the localStorage variable but I got circular reference problems with theJSON.stringify
method.Any tip to manage that?