且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在AngularJS中缓存HTTP“获取”服务响应?

更新时间:2022-04-30 05:02:55

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);
   });
}