Angular: Restore scope from sessionStorage

ぐ巨炮叔叔 提交于 2019-12-30 00:38:08

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/25428170/angular-restore-scope-from-sessionstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!