如何在Angular $ cacheFactory中定义Cache的到期时间

时间:2015-07-16 09:44:53

标签: angularjs caching

我读到了Angular' $ cacheFactory'但无法找到有关设置缓存内容的到期日期的任何文档。

如果我要将所有GET请求缓存30秒,如何在' $ cacheFactory'中定义此怎么办?或者我是否需要自己扩展功能。

3 个答案:

答案 0 :(得分:12)

对于TTL 1h,见下面的例子

添加工厂:

.factory('cacheInterceptor', ['$cacheFactory', function($cacheFactory) {
  var http_ttl_cache = {};
  return {
    request: function(config) {
      var N;
      if (config.timeToLive) {
        config.cache = true;
        N = config.timeToLive;
        delete config.timeToLive;
        if (new Date().getTime() - (http_ttl_cache[config.url] || 0) > N) {
          $cacheFactory.get('$http').remove(config.url);
          http_ttl_cache[config.url] = new Date().getTime();
        }
      }
      return config;
    }
  };
}])

然后init in config推送你的拦截器。 拦截器只是一个注册到该阵列的常规服务工厂。

.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {

  $httpProvider.interceptors.push('cacheInterceptor');

请求示例

$http.get('/permissions.json', {timeToLive: Constant.timeToLive}).then(function(result){

常数是:

.constant('Constant', {
  url: {
    logout: '/auth/logout'
  },
  timeToLive: 60*60*1000
})

答案 1 :(得分:10)

我也遇到了这个问题。默认的$ cacheFactory没有时间(TTL)。

您需要自己实施。但之前,你可以看一看,看看是否有人已经这样做了:

这看起来非常完整 - http://jmdobry.github.io/angular-cache/

如果您真的想要实现自己的解决方案(通过实现自己的$ cacheFactory)并需要一些帮助,请随时提问。

希望它能给你一些线索。

答案 2 :(得分:0)

我认为@miukki回答很棒。将我的修改添加到@Vil

的请求中

我修改了'请求' “cacheInterceptor”的功能'使用$ timeout而不是依赖Date。它允许TTL对请求更加全局化。因此,如果一个请求设置了TTL而第二个请求没有,但数据仍处于缓存状态,则仍将使用它。

.factory('cacheInterceptor', ['$cacheFactory', '$timeout', function($cacheFactory, $timeout) {
  var ttlMap = {};
  return {
    request: function(config) {
      if (config.ttl) {
        var ttl = config.ttl;
        delete config.ttl;
        config.cache = true;

        // If not in ttlMap then we set up a timer to delete, otherwise there's already a timer.
        if (!ttlMap[config.url]) {
          ttlMap[config.url] = true;
          $timeout(ttl)
          .then(function() {
            $cacheFactory.get('$http').remove(config.url);          
            delete ttlMap[config.url];
          });
        }
      }
      return config;
    }
  };
}])