问题描述
我希望能够创建一个自定义AngularJS服务,当其数据对象为空时发出HTTP获取请求,并在成功时填充该数据对象。
I want to be able to create a custom AngularJS service that makes an HTTP 'Get' request when its data object is empty and populates the data object on success.
下次调用该服务时,我想绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
The next time a call is made to this service, I would like to bypass the overhead of making the HTTP request again and instead return the cached data object.
这是
推荐答案
Angular的具有。根据文档:
Angular's $http has a cache built in. According to the docs:
布尔值
因此您可以设置在其选项中缓存
为 true :
$http.get(url, { cache: true}).success(...);
或者,如果您喜欢通话的配置类型:
or, if you prefer the config type of call:
$http({ cache: true, url: url, method: 'GET'}).success(...);
缓存对象
您也可以使用缓存工厂:
Cache Object
You can also use a cache factory:
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
您可以使用自己实现(特别是在使用$ resource时特别方便):
You can implement it yourself using $cacheFactory (especially handly when using $resource):
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}
这篇关于在AngularJS中缓存HTTP“获取”服务响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!