6

当我列出 $cacheFactory 对象时,它有几种方法,但我没有看到实际的键/值缓存。

假设您正在查看 $http 缓存,$cacheFactory($http) 如何获取键列表,或者理想情况下,获取当前缓存的键和值?

4

1 回答 1

2

使用 的装饰器$cacheFactory添加getKeys方法:

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


<body ng-app="decorateExample">

  <script>
  function cacheProvider($provide) 
    {
    // monkey-patches $templateCache to have a keys() method
    $provide.decorator('$templateCache', ['$delegate', cacheDelegator]);
    }
                                          
  function cacheDelegator($delegate) 
    {
    var keys = [], origPut = $delegate.put;

    $delegate.put = function(key, value) 
      {
      origPut(key, value);
      keys.push(key);
      };

    // we would need cache.peek() to get all keys from $templateCache, but this features was never
    // integrated into Angular: https://github.com/angular/angular.js/pull/3760
    // please note: this is not feature complete, removing templates is NOT considered
    $delegate.getKeys = function() 
         {
         return keys;
         };

    return $delegate;
    }
  
angular.module('decorateExample', []);
  
angular.module('decorateExample').config(['$provide', cacheProvider]);
</script>

</body>

参考

于 2016-02-05T06:59:47.170 回答