我的目標是通過在$cacheFactory
中緩存一些靜態JSON對象來使$http
在我的本地文件系統上工作。我希望完全避免網絡請求,並只使用緩存的內容。
問題是$http
正在發出服務器請求,無論緩存內容是否存在。我的代碼如下。
緩存廠
myApp.factory('jsonCache', function($cacheFactory){
// create new cache object
// (tried $cacheFactory.get('$http') as well, but same result)
var cache = $cacheFactory('jsonCache');
// put static value in cache
cache.put('/json/file1.json', {"key":"value"});
return cache;
});
廠使用$ HTTP
myApp.factory('AjaxFactory', function($http, jsonCache){
console.log(jsonCache.info()); // {id: 'jsonCache', size: 1}
// this will make a request to "http://localhost/json/file1.json"
// even though there is an entry for that URL in the cache object
$http.get('/json/file1.json', {cache: jsonCache}).success(/* ... */);
return { /* ... */ };
});
在這一點上,我想這可能是我使用的cache.put()
的數據格式,但不確定。
所以你基本上** **必須做一個'if'。它看起來像'$ http'不會直接從緩存讀取;至少不是第一次得到。 – SteamDev 2015-03-19 16:50:02
@SteamDev首先你必須用數據填充緩存,然後你可以使用緩存數據,而不是再打電話給服務器 – sylwester 2015-03-19 17:32:51
那就是我在緩存工廠的這條線上做的事'cache.put('/ json/file1 .json',{「key」:「value」});',但'$ http'仍然請求file1.json。也許我會創造一個更好的例子來說明問題。 – SteamDev 2015-03-19 17:52:44