3 回答

TA貢獻1868條經驗 獲得超4個贊
cache - {boolean | Object} - 使用$ cacheFactory創建的布爾值或對象,用于啟用或禁用HTTP響應的緩存。有關更多信息,請參閱 $ http Caching。
布爾值
所以你可以在其選項中設置cache
為true:
$http.get(url, { cache: true}).success(...);
或者,如果您更喜歡配置類型的呼叫:
$http({ cache: true, url: url, method: 'GET'}).success(...);
緩存對象
您還可以使用緩存工廠:
var cache = $cacheFactory('myCache');$http.get(url, { cache: cache })
你可以使用$ cacheFactory自己實現它(特別是在使用$ resource時):
var cache = $cacheFactory('myCache');var data = cache.get(someKey);if (!data) { $http.get(url).success(function(result) { data = result; cache.put(someKey, data); });}

TA貢獻1851條經驗 獲得超4個贊
我認為現在有一個更簡單的方法。這為所有$ http請求啟用了基本緩存($ resource繼承):
var app = angular.module('myApp',[]) .config(['$httpProvider', function ($httpProvider) { // enable http caching $httpProvider.defaults.cache = true; }])

TA貢獻1900條經驗 獲得超5個贊
在當前穩定版本(1.0.6)中執行此操作的更簡單方法需要更少的代碼。
設置模塊后添加工廠:
var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
// route setups
});
app.factory('MyCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
現在你可以將它傳遞給你的控制器:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
一個缺點是密鑰名稱也會自動設置,這可能會使清除它們變得棘手。希望他們能以某種方式添加關鍵名稱。
- 3 回答
- 0 關注
- 605 瀏覽
添加回答
舉報