![](/img/trans.png)
[英]Is there a way to get all of the keys out of a cache in Angular, specifically the template cache?
[英]Is there any way to get all the keys in an angular $cacheFactory?
我知道在npm / bower上有另一個名為angular-cache的庫。 但是添加一個新庫是我工作的一個過程。 所以我想使用$ cacheFactory或核心Javascript函數來解決這個問題。
我在stackoverflow中看到了很多用於獲取hasmap的所有鍵的響應,所以我嘗試了這個:
var keys = [];
for(var key in parameterCache) {
keys.push(key);
console.log(key);
}
控制台上的輸出很奇怪。 它們是$ cacheFactory中的函數名稱(刪除,銷毀,信息等)
沒有內置的方法列出$cacheFactory
實例中的所有鍵,並且沒有計划將其包含在核心庫中 ,因此您必須使用諸如angular-cache庫之類的替換或者自己添加這些方法。 我需要將這個功能添加到我的$ http緩存中,我找不到干凈利落的方法(使用裝飾器或其他東西)所以我不得不在我的.run()
塊中使用猴子修補它:
// create a new $cacheFactory instance
var httpWithKeysCacheFactory = $cacheFactory('$httpWithKeys'),
// save the original put() method
originalPut = httpWithKeysCacheFactory.put;
// add a property to hold cache keys
httpWithKeysCacheFactory.keys = [];
// overwrite put() with a custom method
httpWithKeysCacheFactory.put = function (key, value) {
// call original put() and save the key
if (originalPut(key, value)) {
this.keys.push(key);
}
};
// tell $http to use your monkey-patched cache factory
$http.defaults.cache = httpWithKeysCacheFactory;
這樣做允許我從控制器訪問我的緩存鍵,如下所示:
$cacheFactory.get('$httpWithKeys').keys;
注意:這是一種非常天真的方法,它不會檢查密鑰重復項,也不會修改remove()
和removeAll()
方法,以便在從緩存中刪除條目時更新密鑰。
您可以使用此模塊: angular-cache
因此,您可以使用此CacheFactory.keys()返回所有已注冊緩存的ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.