且构网

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

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

更新时间:2023-02-02 17:19:31

您可以创建包装器服务以根据需要进行缓存,例如:

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