在AngularJS中缓存HTTP“获取”服务响应? [英] Cache an HTTP 'Get' service response in AngularJS?

查看:121
本文介绍了在AngularJS中缓存HTTP“获取”服务响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建一个自定义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的 $ http 具有内置缓存。根据文档:

Angular's $http has a cache built in. According to the docs:


缓存 – {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.



布尔值



因此您可以设置在其选项中缓存 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“获取”服务响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆