簡體   English   中英

使Angular中的所有$ http緩存無效

[英]Invalidating all $http caches in Angular

我有一個Angular應用程序,其中包含許多基於Angular內置$resource服務的服務。 其中許多使用cacheFactory來創建自己的獨立緩存。 但是,當有人注銷時,我想要將所有這些(包括命名的緩存和“默認” $http緩存)吹走。 現在我用location.reload(true)完成了這個,這肯定有效,但是如果沒有完全改變應用程序的結構就可以在沒有重新加載的情況下實現它。

為了澄清,我知道如果我在范圍內引用了單個緩存,我可以刪除緩存的值,但我想要做的是全面刪除所有緩存,而不必知道它們是什么一切都叫了。

您可以注入$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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM