取消这样的http请求时:
$scope.runTest = function() {
if (canceler) canceler.resolve();
canceler = $q.defer();
$http({
method: 'GET',
url: 'http://www.google.com/',
timeout: canceler.promise
})
.success(function(data) {
$scope.result.push({msg: "this won't be displayed on cancel"});
})
.error(function(data) {
$scope.result.push({msg: "this will be displayed on cancel"});
});
};
Run Code Online (Sandbox Code Playgroud)
是否可以使取消的HTTP请求具有特定的HTTP代码,如205?它会导致http拦截器以http状态0触发,该状态也用于超时或无网络连接.我希望能够区分拦截器中的两个场景
谢谢!
我最终采用了以下方法:
$scope.runTest = function() {
if (canceler) {
// Set non-zero status for http interceptors
// Using 499, an nginx extension to flag cancelled http requests
// Could be something else like a boolean, using status code for convenience
canceler.promise.status = 499;
// Cancel the request
canceler.resolve();
}
canceler = $q.defer();
$http({
method: 'GET',
url: 'http://www.google.com/',
timeout: canceler.promise
})
.success(function(data) {
// On sucesss
})
.error(function(data) {
// On error
});
};
Run Code Online (Sandbox Code Playgroud)
@Daniel Silva建议,我只是在超时时设置一些东西,将请求标记为已取消.然后在我的http拦截器上:
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'responseError': function(response) {
var statusCode = response.status;
// Get status from timeout, if 0 and timeout present
if (statusCode === 0 && response.config.timeout) {
statusCode = response.config.timeout.status;
}
// Ignore client request cancelled
if (statusCode === 499) {
return response;
}
// Reject via $q, otherwise the error will pass as success
return $q.reject(response);
}
};
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4011 次 |
| 最近记录: |