【问题标题】:When AngularJS caches HTTP requests does it cache the parsed JSON object or the string response itself当 AngularJS 缓存 HTTP 请求时,它会缓存解析的 JSON 对象还是字符串响应本身
【发布时间】:2017-06-27 09:06:37
【问题描述】:

我使用内置的 AngularJS 缓存 I.E. 缓存我的 HTTP 请求

.$http({
    url: "/api/data",
    method: "GET",
    cache: true
})

从我的 API 返回的所有数据都是经过 gzip 压缩的 JSON。一些请求是非常大的未压缩(想想兆字节),并且大量的浏览器时间花费在从字符串转换为 JSON 上。然后我想知道 AngularJS 是如何缓存 HTTP 响应的。如果它只缓存字符串响应,那么每次我访问缓存时,它都必须再次转换为 JSON,这可能会很昂贵。

谁能解释一下 AngularJS 到底缓存了什么,这样我就可以决定如何最好地进行,即对于某些大型调用,将数据缓存为服务中的对象,而不是使用 HTTP 缓存。

【问题讨论】:

  • 应该缓存响应对象,你可以在debug中运行js查看详情
  • 它存储为字符串。 Angular 在其上执行 toJSON 和 fromJSON。这会产生内存峰值,因此我无法使用它。
  • @bhantol 谢谢,有我可以查看的链接或参考资料吗?
  • @Chris docs.angularjs.org/api/ng/service/$http#caching 说它When caching is enabled, $http stores the response from the server using the relevant cache object. The next time the same request is made, the response is returned from the cache without sending a request to the server. 这里响应的含义不仅是数据,还包括标题等,就好像收到了真实的响应一样。响应数组的第二个单元格是数据或错误。在github.com/angular/angular.js/blob/v1.6.2/src/ng/http.js 中结帐sendReq
  • toJSON 和 fromJSON 出现在 $http 中的默认 transformResponse 函数中

标签: javascript angularjs json caching


【解决方案1】:

你可以自己看缓存:

var p = $http({
     url: url,
     method: "GET",
     cache: true
})

p.then(function(response) {
     vm.data = response.data;
     vm.info = $cacheFactory.info();
     console.log($cacheFactory.get('$http'));
     console.log($cacheFactory.get('$http').get(url));
     vm.value = $cacheFactory.get('$http').get(url)[1];
     vm.typeOf = typeof vm.value;
})

“$http”缓存将每个项目存储为一个包含 4 个项目的数组:

  • [0] 响应状态
  • [1] 响应数据
  • [2] response.headers()
  • [3] response.statusText

JSON 数据在被任何响应拦截器解析和转换之前存储为原始字符串。

DEMO on JSFiddle

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多