我试图弄清楚是否有可能$http在它发生之前使用拦截器来取消请求.
有一个按钮可以触发请求,但如果用户双击它,我不希望同一个请求被触发两次.
现在,我意识到有几种方法可以解决这个问题,我们已经有了一个可行的解决方案,我们将$http服务包装在一个服务中,该服务跟踪当前待处理的请求,并使用相同的方法,URL和数据忽略新请求.
基本上这是我试图用拦截器做的行为:
factory('httpService', ['$http', function($http) {
var pendingCalls = {};
var createKey = function(url, data, method) {
return method + url + JSON.stringify(data);
};
var send = function(url, data, method) {
var key = createKey(url, data, method);
if (pendingCalls[key]) {
return pendingCalls[key];
}
var promise = $http({
method: method,
url: url,
data: data
});
pendingCalls[key] = promise;
promise.finally(function() {
delete pendingCalls[key];
});
return promise;
};
return {
post: function(url, data) {
return send(url, data, 'POST');
}
}
}])
Run Code Online (Sandbox Code Playgroud)
当我查看用于$http拦截器的API时,它似乎不是实现此目的的一种方法.我可以访问该config对象,但这是关于它的.
我试图超越拦截器可以在这里使用的界限还是有办法实现它?
根据$http 文档,您可以从请求拦截器返回您自己的配置。
尝试这样的事情:
config(function($httpProvider) {
var cache = {};
$httpProvider.interceptors.push(function() {
return {
response : function(config) {
var key = createKey(config);
var cached = cache[key];
return cached ? cached : cached[key];
}
}
});
}
Run Code Online (Sandbox Code Playgroud)