且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

发布请求后使 $resource 缓存无效

更新时间:2023-02-02 17:36:56

你可以创建一个包装服务来做你想做的缓存,例如:

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