Search code examples
angularjssession-storage

How to prevent the being deleted form service after refresh?


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.


Solution

  • 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.