Invalidate $resource Cache After Post Request

前端 未结 3 1600
眼角桃花
眼角桃花 2020-12-24 14:34

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 15:03

    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

提交回复
热议问题