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

编程入门 行业动态 更新时间:2024-10-24 16:22:35
本文介绍了发布请求后使 $resource 缓存无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 $resource 并缓存 get 请求的结果.我的问题是,在发布请求之后,缓存没有失效.

I am using $resource and caching the results of get requests. My problem is that, after post requests, the cache is not being invalidated.

这里是服务的返回值:

return $resource('http://url/api/url/:id', {}, {
'query' : {
      method : 'GET',
      isArray:true,
      cache : true
    },
'get' : {
  method : 'GET',
  cache : false
}  
})

这是我在控制器中使用的保存方法.如您所见,我正在使用 post 请求上的回调来重新计算查询/名词列表.

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

我想在调用 post 或其他非 get 方法后使缓存无效.我怎么能这样做?这是否已经内置到 $resource 中,还是我需要自己实现?

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:

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

这篇关于发布请求后使 $resource 缓存无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 00:23:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1011355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   resource

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!