3 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
Angular的$ http 內(nèi)置了一個(gè)緩存。根據(jù)文件:
cache - {boolean | Object} - 使用$ cacheFactory創(chuàng)建的布爾值或?qū)ο?/strong>,用于啟用或禁用HTTP響應(yīng)的緩存。有關(guān)更多信息,請(qǐng)參閱 $ http Caching。
布爾值
所以你可以在其選項(xiàng)中設(shè)置cache
為true:
$http.get(url, { cache: true}).success(...);
或者,如果您更喜歡配置類型的呼叫:
$http({ cache: true, url: url, method: 'GET'}).success(...);
緩存對(duì)象
您還可以使用緩存工廠:
var cache = $cacheFactory('myCache');$http.get(url, { cache: cache })
你可以使用$ cacheFactory自己實(shí)現(xiàn)它(特別是在使用$ resource時(shí)):
var cache = $cacheFactory('myCache');var data = cache.get(someKey);if (!data) { $http.get(url).success(function(result) { data = result; cache.put(someKey, data); });}

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

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
在當(dāng)前穩(wěn)定版本(1.0.6)中執(zhí)行此操作的更簡(jiǎn)單方法需要更少的代碼。
設(shè)置模塊后添加工廠:
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');
});
現(xiàn)在你可以將它傳遞給你的控制器:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
一個(gè)缺點(diǎn)是密鑰名稱也會(huì)自動(dòng)設(shè)置,這可能會(huì)使清除它們變得棘手。希望他們能以某種方式添加關(guān)鍵名稱。
- 3 回答
- 0 關(guān)注
- 604 瀏覽
添加回答
舉報(bào)