Angular:从 sessionStorage 恢复范围 [英] Angular: Restore scope from sessionStorage

查看:30
本文介绍了Angular:从 sessionStorage 恢复范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在页面刷新时从 sessionStorage 检索我的搜索和过滤数据.

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

sessionStorage.restorestate 返回 undefined,有人知道为什么吗?

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

推荐答案

当您在 Angular 应用中刷新页面时,就像完全重新启动应用程序.所以要从会话存储中恢复,只需在服务工厂执行时进行即可.

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();
        ...
    }
]);

保存部分已经正确.

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');
    };
});

演示

这篇关于Angular:从 sessionStorage 恢复范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆