How to define expiration time on Cache in Angular $cacheFactory

后端 未结 3 1918
余生分开走
余生分开走 2020-12-19 01:08

I read about the Angular \'$cacheFactory\' but could not find any documentation on setting an expiration date for cached content.

What if I want to cache all GET req

3条回答
  •  孤城傲影
    2020-12-19 01:50

    I think @miukki answer's is great. Adding my modification to the request of @Vil

    I modified the 'request' function of the 'cacheInterceptor' to use $timeout instead of relying on Date. It allows TTL to be more global for requests, So if one request sets a TTL and the 2nd doesn't but data is still in cached, it will still be used.

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

提交回复
热议问题