2014-02-09 33 views
5

嘿我如何緩存x時間這個簡單的對象,我通過$ http($ rootScope.config.app_genres)設置?AngularJS - 緩存rootScope參數,它的值

$http.get($rootScope.config.app_ws+'get/genres',{},{cache:true}).success(function(response) { 
    $rootScope.config.app_genres = response; 
    }); 

我只是想緩存它不重複每次HTTP請求

回答

4

正如$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/

4

H I,(希望角已事內置的,別人可能會增加,但)

我想我們可以其分配到一個新的變量

$rootScope.dataCache = $rootScope.data; 

$rootScope.cacheTimer = 50000; 

你的網站的應用程序始終從$ rootScope.dataCache和日常閱讀,檢查和/或自動更新時CacheTimer已經過去了,到重新調用服務器端並重新分配。

+0

所以數據高速緩存和cacheTimer是本地人? :P – sbaaaang

+0

nope,他們聽起來像他們可以,不,只是你選擇的常規變量名稱。 –

+0

謝謝你,你能否爲社區提供一個可行的例子? :) – sbaaaang

3

我使用此代碼緩存模板

$http.get(/*URL*/, {cache: $templateCache}) 
    .success(function() { ... }) 
    .error(function() { ... }); 

,但也許這將是一個更多你想要做 https://coderwall.com/p/40axlq

3

你可以使用緩存清除你的需求是什麼。可以說,如果你只想緩存x秒。在您添加緩存無效查詢參數值爲

Math.floor(new Date().getTime()/(x * 1000))

請求看起來像

$http.get(url,{cacheBuster: Math.floor(new Date().getTime()/(x * 1000))},{cache:true})