AngularJS$http缓存过期时间

AngularJS$http缓存过期时间,angularjs,Angularjs,您可以为Angular的$http默认缓存系统设置过期时间吗? 我希望URL在缓存中保留1分钟,以便在1分钟后对其发出的任何请求都能从服务器获取新数据。无法设置过期时间。但是你可以手工操作。您必须访问$http缓存: var cache = $cacheFactory.get('$http'); 并删除以下缓存的url: cache.remove(theUrl); 有关更多信息,请参阅。根据这里的$cacheFactory规范 存储Javascript堆内存 逐出算法最近最少使用(LRU)

您可以为Angular的$http默认缓存系统设置过期时间吗?
我希望URL在缓存中保留1分钟,以便在1分钟后对其发出的任何请求都能从服务器获取新数据。

无法设置过期时间。但是你可以手工操作。您必须访问$http缓存:

var cache = $cacheFactory.get('$http');
并删除以下缓存的url:

cache.remove(theUrl);
有关更多信息,请参阅。

根据这里的
$cacheFactory
规范

  • 存储Javascript堆内存
  • 逐出算法最近最少使用(LRU)
  • 生存时间直到页面刷新
  • 支持重新验证
  • 需要远程服务器的合作
另一种解决方案:

使用
$httpProvider
钩住请求

http_ttl_cache={}#保存上次缓存时间
MyApp.config['$httpProvider',($httpProvider)->
$httpProvider.interceptors.push['$cacheFactory',($cacheFactory)->
请求:(配置)->
如果config.params和config.params.\uu缓存__
config.cache=true
N=config.params.\u缓存__
删除config.params.\u缓存__
如果矩()-(http_ttl_缓存[config.url]或0)>1000*N
cache=$cacheFactory.get(“$http”)
cache.remove(config.url)
http\u ttl\u缓存[config.url]=momente()
返回配置
]
]
在控制器中:

#600是600秒
$http.get(“/api/books?limit=100”,
{
参数:{''uuuu缓存''uuuu':600,'foo':'bar'}
}
)

AngularJS的基于过期时间的缓存实现可能如下所示:

MyAngularApp.factory('cache', function($cacheFactory) {    
    const cache = $cacheFactory('expire-cache');

    function get(key, defaultValue = null, expire = null) {    
        let cached = cache.get(key);
        let expired = cached && cached.expire > 0 && cached.expire < performance.now() - cached.created;
       
        if (!cached || expired) {
            cached = {
                value: typeof (defaultValue) === 'function' ? defaultValue() : defaultValue,
                expire: expire,
                created: performance.now()
            }

            if (cache.value !== null && 
                cache.value !== undefined) {

                cache.put(key, cached);
            }
        }
        
        return cache.value;
    }

    return {
        get: get,
        remove: function remove(key) { cache.remove(key) },
        clear: function clear() { cache.removeAll() },
    };    
});
read = cache.get('keyName1', 'my permanent value');
read = cache.get('keyName2', 'my static value for 5 secs', 5000);
read = cache.get('keyName3', () => 'my on time value for 5 secs', 5000);

cache.remove('keyName1'); /* Remove one */

cache.clear(); /* Remove all */