加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 发送请求后$资源缓存无效

发布时间:2020-12-17 07:39:31 所属栏目:安全 来源:网络整理
导读:我正在使用$资源并缓存获取请求的结果.我的问题是,在发布请求后,缓存不会被无效. 以下是服务的返回值: return $resource('http://url.com/api/url/:id',{},{'query' : { method : 'GET',isArray:true,cache : true },'get' : { method : 'GET',cache : fals
我正在使用$资源并缓存获取请求的结果.我的问题是,在发布请求后,缓存不会被无效.

以下是服务的返回值:

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

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

var newNoun = new Noun($scope.noun);
newNoun.$save(function(x) {
  $scope.nouns = Noun.query();
});

我想在调用post或者另一个get-get方法后使缓存无效.我该怎么做?这是否已经内置到$资源中,还是需要自己实现?

您可以创建一个包装服务来执行您想要的缓存,例如:
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({},{
      'get':    { method: 'GET',cache: cache },'query':  { method: 'GET',cache: cache,isArray: true },'save':   { method: 'POST',interceptor: interceptor },'remove': { method: 'DELETE','delete': { method: 'DELETE',});

    return $resource(url,options);
  };
});

然后用cachedResource替换任何$资源.

示例代码:http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读