小编典典

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

angularjs

我有一个Angular应用程序,其中包含基于Angular的内置$resource服务的许多服务。其中许多使用cacheFactory来创建自己的独立缓存。但是,我想$http在有人注销时将所有这些(命名的高速缓存和“默认”
高速缓存)销毁。现在,我可以使用来完成此操作location.reload(true),该功能当然可以工作,但是如果有可能在不完全更改应用程序结构的情况下不重装就可以实现。

需要澄清的是,我知道如果引用范围内的单个缓存,则可以删除缓存的值,但是我想做的是全面删除所有缓存,而不必知道它们的含义。都叫。


阅读 305

收藏
2020-07-04

共1个答案

小编典典

您可以$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();
});

您可以将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;
      });
    }
  ])



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

  });


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="App">



</div>
2020-07-04