javascript AngularJS:如何缓存从 $http 调用返回的 json 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21501367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:02:16  来源:igfitidea点击:

AngularJS: How can I cache json data returned from $http call?

javascriptasp.netjsonangularjscaching

提问by Pawan Pillai

How can I cache json data returned from $http call. I use the following style of $http call:

如何缓存从 $http 调用返回的 json 数据。我使用以下样式的 $http 调用:

$http({
        url: 'SomeWebMethodUrl',
        method: "POST",
        data: "{'query':'somevalue'}",
        headers: { 'Content-Type': 'application/json' }
    }).success(function (data, status, headers, config) {
        //something in success
    }).error(function (data, status, headers, config) {
        //something in error
    });

I looked at the following tutorial: https://coderwall.com/p/40axlqon caching server response from $http call. But it is explaining $http.get() style and will cache data and will not make second $http request if the absolute URL is same.

我查看了以下教程:https: //coderwall.com/p/40axlq关于从 $http 调用缓存服务器响应。但它解释了 $http.get() 样式,并且会缓存数据,如果绝对 URL 相同,则不会发出第二个 $http 请求。

Can I use caching with my style of $http call when my 'data' property is same for same webmethod calls in future? I am using ASP.net ASMX webservice for my WebMethods.

当我的 'data' 属性与以后相同的 webmethod 调用相同时,我可以将缓存与我的 $http 调用风格一起使用吗?我正在为我的 WebMethods 使用 ASP.net ASMX 网络服务。

回答by Geoff Genz

The angular.js cache is designed for HTTP GET calls only. This is consistent with the intent of the HTTP protocol, as HTTP servers don't usually look beyond the URL, the HTTP Method, and Cache-Control headers to determine whether they can respond to a request with cached content. Accordingly, the authors of angular did not extend the caching functionality to other HTTP methods.

angular.js 缓存专为 HTTP GET 调用而设计。这与 HTTP 协议的意图一致,因为 HTTP 服务器通常不会超越 URL、HTTP 方法和 Cache-Control 标头来确定它们是否可以响应具有缓存内容的请求。因此,angular 的作者没有将缓存功能扩展到其他 HTTP 方法。

Another way to look at it is that the angular $cache service is really just a simple key value store, with the URL of the request acting as a key and the response to the HTTP GET request the value that is stored locally instead of on the server.

另一种看待它的方式是,angular $cache 服务实际上只是一个简单的键值存储,请求的 URL 充当键,对 HTTP GET 请求的响应是存储在本地而不是存储在服务器。

When you think of it that way it becomes clear why it's more difficult to cache the response to a POST request. The content returned by the POST request depends not only on the URL, but the POSTed content. To cache that result in a key value store you need a mechanism to create an unique key that identifies both the URL and the data being passed.

当您这样想时,就很清楚为什么缓存对 POST 请求的响应更加困难。POST 请求返回的内容不仅取决于 URL,还取决于 POST 的内容。要将结果缓存到键值存储中,您需要一种机制来创建唯一键来标识 URL 和正在传递的数据。

If you data is simple enough, my suggestion is to write your own cache that is checked before you use the angular $http service. Without knowing more about your data method I can't give you a complete example, but you could do something like this:

如果您的数据足够简单,我的建议是编写您自己的缓存,在您使用 angular $http 服务之前检查该缓存。在不了解您的数据方法的情况下,我无法给您一个完整的示例,但您可以执行以下操作:

angular.module('myModule').service('myDataService', function($cacheFactory, $http) {

  var cache = $cacheFactory('dataCache');

  function success(data, status, headers, config) {
    // some success thing
  }

  function error(data, stats, headers, config) {
    // some error thing
  }

  this.getSomeData = function(url, query) {
    var cacheId = url + '*' + query;
    var cachedData = cache.get(cacheId);
    // Return the data if we already have it
    if (cachedData) {
      success(cachedData);
      return;
    }

    // Got get it since it's not in the cache
    $http({url: url,
           method: 'POST',
           data: {query: query},
           headers: { 'Content-Type': 'application/json' }  // Probably not necessary, $http I think does this 
         }).success(function(data, status, headers, config) {
              // Put this in our cache using our 'unique' id for future use
              cache.put(cacheId, data);
              success(data, status, headers, configs);
         }).error(error);    

  };

});

You would then substitute this wrapper service where you currently use the raw $http service.

然后,您将在当前使用原始 $http 服务的地方替换此包装器服务。

The point is to implement your own cache that understands the 'url+data' as a key before actually calling the $http service.

关键是在实际调用 $http 服务之前实现自己的缓存,将“url+data”理解为键。

回答by Yousef

The usage of POST request used to add new records in the data store, PUT and DELETE modify the status of data store. And it doesn't make sense to cash any of them.

POST请求的用法用于在数据存储中添加新记录,PUT和DELETE修改数据存储的状态。兑现其中任何一个都没有意义。

Only GET retrieve data without modifying data store. And this makes sense to cash it's response.

只获取数据而不修改数据存储。这对兑现它的回应是有意义的。