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