Invalidate $resource Cache After Post Request

让人想犯罪 __ 提交于 2019-11-30 00:17:28

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);
  };
});

Then replace any $resource with cachedResource.

Example plunker: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview

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:

app.factory('Steps', function (CachedResource) {
    return CachedResource('/steps/:stepId', {}, {
        save: { method: 'POST', params: { stepId: '@stepId' } }
    });
});

In this case, this definition of save would be replaced by the one present in CachedResource.

Solution

But it can be fixed easily from Angular 1.4 by replacing

actions = angular.extend({}, actions, {

with

actions = angular.merge({}, actions, {

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:

actions = angular.merge({}, { /* default options get, query, etc. */ }, actions);

With this solution, the following will work as expected (i.e. use DESTROY instead of default DELETE when calling remove):

app.factory('Steps', function (CachedResource) {
    return CachedResource('/steps/:stepId', {}, {
        remove: { method: 'DESTROY' }
    });
}); 
gkalpak

$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.:

var key = '...the key you want to remove, e.g. `/nouns/5`...';
$cacheFactory.get('$http').remove(key);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!