正如$http documentation所述,您可以通過緩存配置選項提供您自己的緩存對象實例。
這是$cacheFactory
,我重寫put
方法,以便在TIMEOUT
之後清除緩存。請注意,這僅適用於一個網址。我將離開使這個計時器緩存對象通用作爲練習。
function Ctrl($scope, $http, $cacheFactory, $timeout) {
var timedCache = $cacheFactory('myCache'),
TIMEOUT = 5000,
cacheTimer = null;
timedCache._put = timedCache.put;
timedCache.put = function (key, val) {
console.log('caching', key);
$timeout.cancel(cacheTimer);
cacheTimer = $timeout(function() {
console.log('clearing cache for', key);
timedCache.remove(key);
}, TIMEOUT, false);
timedCache._put(key, val);
};
$scope.request = function() {
$http.get('/echo/json', {
cache: timedCache
})
.success(function (data) {
console.log('received', data);
});
};
}
下面是這個工作的小提琴:http://jsfiddle.net/sirhc/jvLPX/
所以數據高速緩存和cacheTimer是本地人? :P – sbaaaang
nope,他們聽起來像他們可以,不,只是你選擇的常規變量名稱。 –
謝謝你,你能否爲社區提供一個可行的例子? :) – sbaaaang