所有
我正在尝试设置一个全局httpInterceptor,以便在出现客户端超时而不是服务器超时时显示自定义弹出消息。我发现这篇文章:Angular $http : setting a promise on the 'timeout' config,并将其转换为httpInterceptor,但它没有按预期工作,并且有一些奇怪的行为。
$provide.factory('timeoutHttpInterceptor', function ($q, $translate, $injector) {
var timeout = $q.defer();
var timedOut = false;
setTimeout(function () {
timedOut = true;
timeout.resolve();
}, 10000);
return {
request: function (config) {
config.timeout = timeout.promise;
return config;
},
response: function(response) {
return response;
},
responseError: function (config) {
if(timedOut) {
var toastr = $injector.get('toastr');
toastr.custom('network', $translate('title'), $translate('label'), { timeOut: 5000000000000, closeButton: true, closeHtml: '<button></button>' });
return $q.reject({
error: 'timeout',
message: 'Request took longer than 1 second(s).'
});
}
},
};
});
答案 0 :(得分:4)
您可以使用返回承诺的$timeout
服务并将其分配给config.timeout
。看看下面的代码。
.factory('timeoutInterceptor', ['$q','$timeout', function($q,$timeout) {
return {
request: function(config) {
//assign a promise with a timeout, and set timedOut flag, no need to trigger $digest, thus false as 3rd param
config.timeout = $timeout(function(){ config.timedOut = true },2000,false);
return config;
},
responseError :function(rejection) {
if(rejection.config.timedOut){ //if rejected because of the timeout - show a popup
alert('Request took longer than 1 second(s).');
}
return $q.reject(rejection);
}
};
以下是完整的工作示例:http://jsfiddle.net/2g1y4bk9/