【发布时间】:2017-02-23 16:10:40
【问题描述】:
我阅读了有关 Angular '$cacheFactory' 的信息,但找不到任何有关为缓存内容设置到期日期的文档。
如果我想将所有 GET 请求缓存 30 秒,如何在“$cacheFactory”中定义它,或者我是否需要自己扩展功能。
【问题讨论】:
我阅读了有关 Angular '$cacheFactory' 的信息,但找不到任何有关为缓存内容设置到期日期的文档。
如果我想将所有 GET 请求缓存 30 秒,如何在“$cacheFactory”中定义它,或者我是否需要自己扩展功能。
【问题讨论】:
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;
}
};
}])
然后在配置中初始化推送你的拦截器。 拦截器只是注册到该数组的常规服务工厂。
.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
})
【讨论】:
params 内部的 option 对象,但它可以简单地修复。
我也遇到了这个问题。默认的 $cacheFactory 没有生存时间 (TTL)。
您需要自己实现。但在此之前,您可以环顾四周,看看是否有人已经这样做了:
这个看起来很完整 - http://jmdobry.github.io/angular-cache/
如果您真的想实现自己的解决方案(通过实现自己的 $cacheFactory)并需要帮助,请随时提出。
希望它能给你一些线索。
【讨论】:
我认为@miukki 的回答很棒。将我的修改添加到@Vil 的请求中
我修改了 'cacheInterceptor' 的 'request' 函数以使用 $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;
}
};
}])
【讨论】: