问题描述
限时送ChatGPT账号..我正在使用 $resource 并缓存 get 请求的结果.我的问题是,在发布请求之后,缓存没有失效.
I am using $resource and caching the results of get requests. My problem is that, after post requests, the cache is not being invalidated.
这里是服务的返回值:
return $resource('http://url/api/url/:id', {}, {
'query' : {
method : 'GET',
isArray:true,
cache : true
},
'get' : {
method : 'GET',
cache : false
}
})
这是我在控制器中使用的保存方法.如您所见,我正在使用 post 请求上的回调来重新计算查询/名词列表.
Here is the save method I am using inside my controller. As you can see, I'm using the callback on the post request to recalculate the query/list of nouns.
var newNoun = new Noun($scope.noun);
newNoun.$save(function(x) {
$scope.nouns = Noun.query();
});
我想在调用 post 或其他非 get 方法后使缓存无效.我怎么能这样做?这是否已经内置到 $resource 中,还是我需要自己实现?
I would like to invalidate the cache after calling post or another non-get method. How could I do this? Is this already built into $resource or do I need to implement it on my own?
推荐答案
你可以创建一个包装服务来做你想做的缓存,例如:
You could create a wrapper service to do the caching like you want, for example:
app.factory('cachedResource', function ($resource, $cacheFactory) {
var cache = $cacheFactory('resourceCache');
var interceptor = {
response: function (response) {
cache.remove(response.config.url);
console.log('cache removed', response.config.url);
return response;
}
};
return function (url, paramDefaults, actions, options) {
actions = angular.extend({}, actions, {
'get': { method: 'GET', cache: cache },
'query': { method: 'GET', cache: cache, isArray: true },
'save': { method: 'POST', interceptor: interceptor },
'remove': { method: 'DELETE', interceptor: interceptor },
'delete': { method: 'DELETE', interceptor: interceptor },
});
return $resource(url, paramDefaults, actions, options);
};
});
然后将任何 $resource
替换为 cachedResource
.
Then replace any $resource
with cachedResource
.
示例 plunker: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview
这篇关于发布请求后使 $resource 缓存无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论