【问题标题】:How to check localStorage before ngResource makes a request?如何在 ngResource 发出请求之前检查 localStorage?
【发布时间】:2015-03-31 04:11:58
【问题描述】:

如何在ngResource 发出请求之前检查 localStorage?我希望我的资源对象在向服务器发出请求之前检查本地存储。我想将来自服务器的初始响应存储在本地存储中,然后如果用户重新加载页面,则不必再次发出请求,而是将其从本地存储中拉出。

(function (angular) {
'use strict';

angular.module('myApp')
.factory('accountResource', function($resource) {

var entity = 'account';
var serverUrl = 'my/url/to/thing/';
var entityUrl = serverUrl + entity;
var resource = $resource(entityUrl + '/', {});

return {
  get: function() {

      //I am thinking about doing a check in here but wondered if there is a better way 
      return resource.get().$promise;
 }
};

});

}(angular));

【问题讨论】:

  • 您能提供到目前为止您使用过的代码吗?
  • 我添加了一些我的代码

标签: angularjs ngresource


【解决方案1】:

我认为您在代码中留下的评论是处理此问题的好方法:

get: function() {
    var fromStorage = localStorage.getItem('foo');

    return fromStorage ? fromStorage : resource.get().$promise;
 }

然后,在你的 promise 的解析回调中,你应该将值存储在 localStorage 中。

【讨论】:

  • 我正在考虑在那里处理它,我只是认为必须有更好的方法来做到这一点。
  • 您可以创建一个服务,该服务将成为您的 accountResource 的依赖项,该服务将使用密钥检查值是否存在,并且您可以在您的应用程序中重复使用它,但您仍然需要在你的 get 方法。
  • resource.get().$promise; 中的resource 是什么?
【解决方案2】:

我猜angular-cache 应该是你最好的选择。看看Using angular-cache with $http 部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2021-11-08
    • 2010-12-10
    相关资源
    最近更新 更多