【问题标题】:AngularJS: How can I cache json data returned from $http call?AngularJS:如何缓存从 $http 调用返回的 json 数据?
【发布时间】:2014-02-01 17:45:10
【问题描述】:

如何缓存 $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
    });

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

当我的“数据”属性与将来相同的 webmethod 调用相同时,我可以在我的 $http 调用样式中使用缓存吗?我正在为我的 WebMethods 使用 ASP.net ASMX 网络服务。

【问题讨论】:

  • 感谢@allenhwkim 我尝试使用 cache:true 参数,但 $http 调用仍然在每次调用时发生(而且我没有刷新浏览器并在单击某些按钮时一次又一次地调用它) .

标签: javascript asp.net json angularjs caching


【解决方案1】:

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

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

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

如果您的数据足够简单,我的建议是编写您自己的缓存,在您使用 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);    

  };

});

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

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

【讨论】:

  • 这将是很酷的把 $http 拦截器这样你可以使用 $http 仍然$httpProvider.interceptors.push(function(){return {'request': function(config) { /*Cache Magic*/ });
  • 很好地解释了为什么角度缓存 GET v. POST
【解决方案2】:

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

仅 GET 检索数据而不修改数据存储。这对兑现它的回应是有意义的。

【讨论】:

    猜你喜欢
    • 2016-10-16
    • 2017-05-21
    • 2015-08-10
    • 2015-04-19
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多