【问题标题】:Angular $http caching: How to identify a cached response vs actual $http.getAngular $http 缓存:如何识别缓存响应与实际 $http.get
【发布时间】:2015-05-22 13:10:43
【问题描述】:

我在 Ionic 应用程序中使用 Angular $http.get() 对外部服务进行 API 调用,并实现了 CacheFactory 插件以使缓存更具可配置性。

一切正常,如果我向相同的端点重复 API 请求,CacheFactory 会返回缓存的响应,并且我在浏览器控制台中看不到实际的 HTTP 请求,直到缓存过期时间过去。

但我希望能够确定我正在使用的数据是来自缓存还是来自新的 HTTP 请求。我该怎么做?

让控制台记录了$http.get() 的输出,我没有看到任何有用的信息,实际上来自缓存或 HTTP 调用的响应对象是相同的。

感谢您的任何想法。

【问题讨论】:

  • 只是一个想法,因为我没有时间玩这个想法,但是 - http拦截器可以帮助吗?我想知道当缓存处理请求时它们是否会被忽略(这可以帮助您推断缓存是否最近用于特定请求);或者,如果您可以使用一个时间戳将时间戳附加到标头属性或可能保留在缓存中的内容,并且您可以检查请求是否“新鲜”...
  • 否则,我注意到jmdobry.github.io/angular-cache(您指的是angular-cacheCacheFactory 插件吗?)有一个onExpire 回调,我认为可能会有一些用处...
  • 我认为检查 $http 缓存是否已经有与请求关联的键可能会有所帮助。

标签: angularjs caching angular-cache


【解决方案1】:

您可以使用 memorize 您的请求的输入,因此当您调用 get 方法时,如果 memorizer 对象包含与请求参数的哈希形式相等的键,那么您知道该请求将被缓存,只要它包含与之前的其他请求相同的参数。在每个键下,您可以保存一个时间戳来计算自该请求第一次完成到现在的毫秒数。

// some where on your code

app.factory('MyMemorizer', ['EXPIRATION_CACHE_TIME', function 

(EXPIRATION_CACHE_TIME) {
// EXPIRATION_CACHE_TIME constant with the milliseconds of the expiration cached
var memo = {};
  return {
    entryExist: function (obj) {
      var timestamp = getEntry(inputs),
      timeDelta = Date.now() - timestamp;
      return timeDelta > EXPIRATION_CACHE_TIME);
    } 

  };

  function getEntry(obj) {
      var hash = createHash(obj);
      if (memo.hasOwnProperty) {
        return memo[hash];
      }

      memo[hash] = Date.now();
      return memo[hash];
    }


  function createHash(obj) {
   var arr = [];
   for (prop in obj) {
     if (obj.hasOwnProperty(prop)) {
       arr.push(encodeURIComponent(prop) + '=' + encodeURIComponent(obj[prop]));
     }
   }

   return arr.join('&');
  }

});

然后将其注入控制器或服务或您需要的地方。

function invokeGetRequest (inputs) {

  // ... do your request

  if (MyMemorizer.entryExist(inputs)) {
    // request is cached
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 2011-04-21
    • 1970-01-01
    • 2018-03-16
    • 2023-02-12
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多