【问题标题】:Angular: Restore scope from sessionStorageAngular:从 sessionStorage 恢复范围
【发布时间】:2014-10-15 04:41:15
【问题描述】:

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

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

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

【问题讨论】:

  • 在您的 plnkr 中似乎没有调用 sessionStorage 设置代码
  • @ExplosionPills:你是对的,对不起。它在我更改路线但 sessionStorage.restorestate 始终未定义时触发。
  • plunker 不使用ngRoute,因此不能进行任何路由更改。另外,我看不到任何将sessionStorage.restorestate 设置为任何东西的代码行,所以它永远不会是"true"。是否缺少某些代码?
  • @HugoWood 很好,我正试图让它与我从这篇文章中得到的东西一起工作:stackoverflow.com/a/16559855
  • 赞成该答案的人可能没有测试它,因为它根本不起作用,而且远非该问题的最佳答案。 OP 只想在更改视图时保留数据。只需将数据放入服务中即可。 想在刷新时保存。完全不同。

标签: angularjs sessionstorage


【解决方案1】:

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

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

DEMO

【讨论】:

  • Ty 对于这个答案,它就像一个魅力,会尝试让它动态化,所以我不需要每次都需要新服务。
  • 我在“service.state”引用中遇到错误:ReferenceError: service is not defined。有什么帮助吗?我从哪里获得service 对象?
  • @AbhishekSaini service 是工厂返回的对象。看看答案中链接的演示(从问题中的那个分叉而来)。
猜你喜欢
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2018-03-24
相关资源
最近更新 更多