Search code examples
angularjssessionstorage

Angular: Restore scope from sessionStorage


I am trying to retrieve my search and filter data from sessionStorage when the page refreshes.

sessionStorage.restorestate returns undefined, does anyone know why?

app.run(function($rootScope) {
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      if (sessionStorage.restorestate == "true") {
        $rootScope.$broadcast('restorestate'); //let everything know we need to restore state
        sessionStorage.restorestate = false;
      }
    });

    //let everthing know that we need to save state now.
    window.onbeforeunload = function(event) {
      $rootScope.$broadcast('savestate');
    };
  });

Plunkr: http://plnkr.co/edit/oX4zygwB0bDpIcmGFgYr?p=preview


Solution

  • When you refresh the page in an Angular app, it is like completely rebooting the application. So to restore from the session storage, just do it when the service factory executes.

    app.factory('CustomerSearchService', ['$rootScope',
        function($rootScope) {
            ...
            function restoreState() {
                service.state = angular.fromJson(sessionStorage.CustomerSearchService);
            }
            if (sessionStorage.CustomerSearchService) restoreState();
            ...
        }
    ]);
    

    The saving part was already correct.

    app.factory('CustomerSearchService', ['$rootScope',
        function($rootScope) {
            ...
            function saveState() {
                sessionStorage.CustomerSearchService = angular.toJson(service.state);
            }
            $rootScope.$on("savestate", saveState);
            ...
        }
    ]);
    
    app.run(function($rootScope) {
        window.onbeforeunload = function(event) {
          $rootScope.$broadcast('savestate');
        };
    });
    

    DEMO