Reputation: 3231
I'm using $sessionStorage
in a service in angular to store date and fetch it in another page. (I'm using SPA).
I can get the data perfectly inside the page, but when I refresh the page , the data from the service is deleted.
Why angular deletes the data from the service? And what should I do to kee p it after I refresh the page?
Thank you.
Upvotes: 1
Views: 1673
Reputation: 6335
Basically when a page is refreshed, angular reloads, services reload and all the data is lost, that is normal behavior for JavaScript stuff.
It's like you are starting from scratch basically. What you need is a way to persist data on reload and you can use something like local storage for example to persist and retrieve data.
Have a look at this for some examples:
Storing Objects in HTML5 localStorage
Upvotes: 1
Reputation: 2778
COOKIES SOLUTION
Whether using cookies is not a "wide" solution, it can solve your question without a server or a database.
Take care that if the user empties temporary internet files, data will be erased, or if the cookie is not permanent, data will be erased when finish date has arrived
First, you need to import ngCookies to your angular app
bower install angular-cookies --save
After that, remember to import the angular cookies scripts:
<script src="path/to/angular.js"></script>
<script src="path/to/angular-cookies.js"></script>
And add the dependency:
angular.module('app', ['ngCookies']);
After that, you will be able to call the ngCookies method from angular, and then store and recover the data stored in the cookie:
The example on angularJS API:
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
Hope it helps.
Anyway, IMO, installing a server-side with a DB should be the right solution if you really want to save info from the users.
Upvotes: 1