Angular: Restore scope from sessionStorage

后端 未结 1 994
不思量自难忘°
不思量自难忘° 2020-12-28 22:25

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

sessionStorage.restorestate returns undefined, does anyone know why?

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 22:49

    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

    0 讨论(0)
提交回复
热议问题