在 AngularJS 中缓存 HTTP 'Get' 服务响应? [英] Cache an HTTP 'Get' service response in AngularJS?
问题描述
我希望能够创建一个自定义 AngularJS 服务,该服务在其数据对象为空时发出 HTTPGet"请求并在成功时填充数据对象.
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's $http has a cache built in. According to the docs:
cache – {boolean|Object} – 使用 $cacheFactory 创建的布尔值或对象,用于启用或禁用 HTTP 响应的缓存.看$http 缓存了解更多信息.
cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
布尔值
因此您可以在其选项中将 cache
设置为 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 })
您可以使用 $cacheFactory 自己实现它(尤其是在使用 $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 'Get' 服务响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!