[英]Angular js - cache a rootScope param and it's value
嘿我如何緩存x時間這個我通過$ http($ rootScope.config.app_genres)設置的簡單對象?
$http.get($rootScope.config.app_ws+'get/genres',{},{cache:true}).success(function(response) {
$rootScope.config.app_genres = response;
});
我只想緩存它,以便每次http請求都不重復
H i,(希望Angular內置一些東西,其他人可以添加)
我想我們可以將它分配給一個新變量
$rootScope.dataCache = $rootScope.data;
$rootScope.cacheTimer = 50000;
您的網站應用程序始終從$ rootScope.dataCache讀取,並在CacheTimer過去時檢查和/或自動更新例程,以調用服務器端並重新分配。
?
如$ http文檔中所述 ,您可以通過緩存配置選項提供自己的緩存對象實例。
這是一個$cacheFactory
,我覆蓋put
方法,以便在TIMEOUT
之后清除緩存。 請注意,這僅適用於一個URL。 我將把這個計時器緩存對象留作通用作為練習。
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/
我使用此代碼來緩存模板
$http.get(/*URL*/, {cache: $templateCache})
.success(function () { ... })
.error(function () { ... });
但也許這個會更多你想要做的事https://coderwall.com/p/40axlq
您可以根據需要使用緩存清除。 讓我們說如果你想只緩存x秒。 您使用值添加緩存清除查詢參數
Math.floor(new Date().getTime() / (x * 1000))
請求看起來像
$http.get(url,{cacheBuster: Math.floor(new Date().getTime() / (x * 1000))},{cache:true})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.