2015-03-09 16 views
5

Khi tôi liệt kê đối tượng $ cacheFactory nó có một vài phương thức, nhưng tôi không thấy bộ đệm khóa/giá trị thực.Lấy chìa khóa từ Angular cacheFactory

Giả sử bạn đang xem bộ nhớ cache $ http, $ cacheFactory ($ http) làm cách nào để có danh sách khóa hoặc lý tưởng, khóa và giá trị hiện được lưu trong bộ nhớ cache?

+0

Câu hỏi thú vị, tôi đã tự hỏi tương tự! – teone

Trả lời

2

Sử dụng trang trí của $cacheFactory để thêm một phương pháp 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>

Tài liệu tham khảo

+0

Đây là một gợi ý rất hay, nhưng tiếc là nó chỉ hoạt động với '$ templateCache' và không thể áp dụng cho các bộ đệm khác như' $ http'. Nếu bạn muốn thay đổi đối tượng bộ nhớ cache mà dịch vụ '$ http' sử dụng thì bạn nên tạo một và tự vá lỗi bằng các phương thức mà bạn cần. – n1313

Các vấn đề liên quan