使Angular中的所有$ http缓存无效

Cas*_*sey 8 javascript caching angularjs

我有一个Angular应用程序,其中包含许多基于Angular内置$resource服务的服务.其中许多使用它cacheFactory来创建自己的独立缓存.但是,$http当有人注销时,我想要将所有这些(包括命名的缓存和"默认" 缓存)都吹走.现在我正在实现这一点location.reload(true),这肯定有效,但如果没有完全改变应用程序的结构,如果没有重新加载就可以实现它.

为了澄清,我知道如果我在范围内引用了单个缓存,我可以删除缓存的值,但我想要做的是全面删除所有缓存,而不必知道它们是什么一切都叫了.

PSL*_*PSL 6

您可以$cacheFactory从工厂构造函数中注入并获取缓存对象(例如:),$cacheFactory.get('$http')并用于removeAll()清理所有缓存.destroy()如果要完全删除缓存对象,请使用.

为了获得所有的cacheObject id,你可以使用$cacheFactory.info()它返回带有每个缓存对象的摘要信息的对象{id:'cacheObjId', size:'cacheSize'}.

例:-

angular.forEach($cacheFactory.info(), function(ob, key) {
   $cacheFactory.get(key).removeAll();
});
Run Code Online (Sandbox Code Playgroud)

你可以添加removeAll/ destroyAll功能到cacheFactory,这样你就可以在其他地方通过装饰来使用它$cacheFactory,就像这样.

.config(['$provide',
    function($provide) {
      $provide.decorator('$cacheFactory', function($delegate) {
        $delegate.removeAll = function() {
          angular.forEach($delegate.info(), function(ob, key) {
            $delegate.get(key).removeAll();
          });
        }

        $delegate.destroyAll = function() {
          angular.forEach($delegate.info(), function(ob, key) {
            $delegate.get(key).destroy();
          });
        }
        return $delegate;
      });
    }
  ])
Run Code Online (Sandbox Code Playgroud)

angular.module('App', [])
  .config(['$provide',
    function($provide) {
      $provide.decorator('$cacheFactory', function($delegate) {
        $delegate.removeAll = function() {
          angular.forEach($delegate.info(), function(ob, key) {
            $delegate.get(key).removeAll();
          });
        }

        $delegate.destroyAll = function() {
          angular.forEach($delegate.info(), function(ob, key) {
            $delegate.get(key).destroy();
          });
        }
        return $delegate;
      });
    }
  ])
  .run(function($cacheFactory) {
    var value = 123;
    $cacheFactory('cache1').put('test', value);
    $cacheFactory('cache2').put('test', value);
    console.log($cacheFactory.info());
    $cacheFactory.removeAll();
    console.log($cacheFactory.info());
  });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">

</div>
Run Code Online (Sandbox Code Playgroud)