AngularJs资源保存/缓存

时间:2015-08-22 05:16:20

标签: angularjs rest

AngularJs在资源结果中保存或缓存临时的最佳方法是什么,需要资源结果来获取它而不需要在服务器中反复使用相同资源的多个指令?

想象一下,有5个指令,所有这些指令都需要资源

的结果

http://foo.com/accounts

这将返回一个json帐户(REST API GET方法)。

缓存此资源结果或将其保存到变量的最佳做法是什么,然后每个指令从此变量获取数据,并避免每1分钟多次访问其余API(因此缓存在1分钟后到期)

非常感谢。

1 个答案:

答案 0 :(得分:2)

有几种方法可以实现这一点,但是一种简单的自包含方式就是这样:

app.factory('myFactory', function($http) {
  var THRESHOLD = 60000; // 60 seconds
  var request = null;
  var timestamp;

  var service = {
    getResource: function() {
      var now = new Date().getTime();

      // only make a request if we haven't made one yet
      // or if its been longer than 60 seconds since the last request
      if(request === null || timestamp && now - timestamp > THRESHOLD) {
        timestamp = now;
        request = $http.get('http://some.service.com/resource');
      }

      // we're always returning a promise, once its resolved any service that
      // calls getResource won't have to wait for the request unless its been
      // over 60 seconds since the last one.
      return request;
    }
  }

  return service;
});

此处的基本演示(稍微修改以模拟http请求):http://plnkr.co/edit/QncVlV?p=linter