Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys from Angular cacheFactory

When I list out the $cacheFactory object it has several methods, but I do not see the actual key/value cache.

Assuming you are looking at the $http cache, $cacheFactory($http) how can you get a list of keys or ideally, keys and values that are currently cached?

like image 201
eeejay Avatar asked Mar 09 '15 19:03

eeejay


1 Answers

Use a decorator of the $cacheFactory to add a getKeys method:

<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>

References

  • AngularJS Issue #3760: Update cacheFactory.js: Added peek() for returning all keys

  • Decorate Core Directives in Angular

like image 139
Paul Sweatte Avatar answered Oct 13 '22 00:10

Paul Sweatte