1

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

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

但我希望能够确定我正在使用的数据是来自缓存还是来自新的 HTTP 请求。我怎样才能做到这一点?

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

任何想法都非常感激。

4

1 回答 1

0

您可以使用 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
  }

}
于 2015-05-22T14:46:06.887 回答