asg*_*oth 312
cache - {boolean | Object} - 使用$ cacheFactory创建的布尔值或对象,用于启用或禁用HTTP响应的缓存.有关更多信息,请参阅 $ http Caching.
所以你可以在其选项中设置cache为true:
$http.get(url, { cache: true}).success(...);
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢配置类型的呼叫:
$http({ cache: true, url: url, method: 'GET'}).success(...);
Run Code Online (Sandbox Code Playgroud)
您还可以使用缓存工厂:
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
Run Code Online (Sandbox Code Playgroud)
你可以使用$ 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);
});
}
Run Code Online (Sandbox Code Playgroud)
gsp*_*tel 48
我认为现在有一个更简单的方法.这为所有$ http请求启用了基本缓存($ resource继承):
var app = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
// enable http caching
$httpProvider.defaults.cache = true;
}])
Run Code Online (Sandbox Code Playgroud)
Jam*_*emp 12
在当前稳定版本(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');
});
Run Code Online (Sandbox Code Playgroud)
现在你可以将它传递给你的控制器:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
Run Code Online (Sandbox Code Playgroud)
一个缺点是密钥名称也会自动设置,这可能会使清除它们变得棘手.希望他们能以某种方式添加关键名称.
如果您喜欢$ http的内置缓存但需要更多控制,请查看库angular-cache.您可以使用它来通过生存时间,定期清除以及将缓存持久保存到localStorage以便跨会话可用的选项无缝扩充$ http缓存.
FWIW,它还提供了工具和模式,使您的缓存成为一种更动态的数据存储,您可以将其作为POJO进行交互,而不仅仅是默认的JSON字符串.目前还无法评论该选项的效用.
(然后,最重要的是,相关的库角度数据是$ resource和/或Restangular的替代品,并且取决于角度缓存.)
由于AngularJS工厂是单身,你可以简单地存储HTTP请求的结果,检索下一个你的服务被注入一些时间.
angular.module('myApp', ['ngResource']).factory('myService',
function($resource) {
var cache = false;
return {
query: function() {
if(!cache) {
cache = $resource('http://example.com/api').query();
}
return cache;
}
};
}
);
Run Code Online (Sandbox Code Playgroud)