发布请求后使$ resource缓存无效 [英] Invalidate $resource Cache After Post Request
问题描述
我正在使用$ 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.com/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);
};
});
然后用cachedResource
替换任何$resource
.
示例监听器: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview
这篇关于发布请求后使$ resource缓存无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!