【问题标题】:Invalidating all $http caches in Angular使 Angular 中的所有 $http 缓存失效
【发布时间】:2015-09-19 01:06:59
【问题描述】:

我有一个 Angular 应用程序,其中包含许多基于 Angular 内置 $resource 服务的服务。其中许多使用cacheFactory 创建自己的独立缓存。但是,当有人注销时,我想清除所有这些(命名缓存和“默认”$http 缓存)。现在我正在使用location.reload(true) 完成此操作,这当然有效,但如果可以在不完全改变应用程序结构的情况下实现它,那么无需重新加载就很好。

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

【问题讨论】:

    标签: javascript angularjs caching


    【解决方案1】:

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

    为了获取所有缓存对象的 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>

    【讨论】:

    • 在 angular 1.2.X 中有没有?
    • @pankajparkar 是的,它可用。
    • 但是等一下……然后我必须单独检索每个命名的缓存,不是吗?
    • 这当然是一个合理的选择,尽管我想在一个地方做。我想改变 $cacheFactory 的提供者可以实现这一点。
    • 对尝试此操作的其他人的一个提示:您应该免除模板缓存;如果你不这样做,你就会开始遇到奇怪的错误。
    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2011-01-13
    • 2017-09-08
    • 2022-01-23
    • 2019-12-06
    • 1970-01-01
    相关资源
    最近更新 更多