问题描述
我试图找出是否有可能使用 $ HTTP
拦截取消请求,甚至发生之前。
I'm trying to figure out if it is possible to use a $http
interceptor to cancel a request before it even happens.
有一个按钮触发一个请求,但是如果用户双击它,我不希望同样的请求得到触发两次。
现在,我才知道有几种方法来解决这个问题,而且我们已经有了 $ HTTP
在保持请求的跟踪服务工作的解决方案,我们换了目前悬而未决,简单地忽略用同样的方法,URL和数据的新的要求。
Now, I realize that there's several ways to solve this, and we do already have a working solution where we wrap $http
in a service that keeps track of requests that are currently pending and simply ignores new requests with the same method, url and data.
基本上,这是我想用一个拦截器做的行为:
Basically this is the behaviour I am trying to do with an interceptor:
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');
}
}
}])
当我在看的 $ HTTP
的API截击它似乎没有一种方法来实现这一目标。我有机会获得配置
的对象,但仅此而已。
When I look at the API for $http
interceptors it does not seem to be a way to achieve this. I have access to the config
object but that's about it.
我是在尝试的东西可以用来拦截范围之外一步这里还是有办法做到这一点?
Am I attempting to step outside the boundaries of what interceptors can be used for here or is there a way to do it?
推荐答案
根据,你可以请求拦截回你自己的配置。
according to $http documentation, you can return your own config from request interceptor.
尝试是这样的:
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];
}
}
});
}
这篇关于取消以$拦截HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!