I am using $resource and caching the results of get requests. My problem is that, after post requests, the cache is not being invalidated.
Here is the return value from the service:
return $resource('http://url.com/api/url/:id', {}, {
'query' : {
method : 'GET',
isArray:true,
cache : true
},
'get' : {
method : 'GET',
cache : false
}
})
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();
});
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:
Then replace any
$resource
withcachedResource
.Example plunker: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview
$resource
is using the default cache for$http
.You can access it using:
$cacheFactory.get('$http')
You can remove a key value pair, using the returned caches
remove({string} key)
method.E.g.:
While @runTarm's answer above is great, it does not allow actions to be easily customized from the inheriting service, e.g. the following would not be possible:
In this case, this definition of
save
would be replaced by the one present inCachedResource
.Solution
But it can be fixed easily from Angular 1.4 by replacing
with
so that both objects are deep-merged.
Even better solution
In the above scenario, action options defined in CachedResource would be preferred over custom configuration in inheriting services. To fix that, switch the order of arguments passed to
merge
:With this solution, the following will work as expected (i.e. use
DESTROY
instead of defaultDELETE
when callingremove
):