我有一个 Angular 应用程序,其中包含许多基于 Angular 内置的服务$resource
服务。其中许多使用cacheFactory
创建自己的独立缓存。然而,我想把所有这些都吹走(命名的缓存和“默认”$http
当有人注销时缓存)。现在我正在完成这个location.reload(true)
,这当然有效,但是如果可以在不完全改变应用程序结构的情况下实现它,那么最好在不重新加载的情况下实现它。
为了澄清,我知道如果我在范围内引用了单个缓存,我可以删除缓存的值,但我想要做的是全面删除所有缓存,而不必知道它们是什么。都叫了。
你可以注射$cacheFactory并从工厂构造函数获取缓存对象(例如:$cacheFactory.get('$http')
)并使用removeAll()
清理所有缓存。使用destroy()
如果您想完全删除缓存对象。
为了获取所有的cacheObject 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)