我正在 Angular js 中使用 $http 进行 ajax 调用。我已经在其中实现了超时。但是我想在连接超时时向用户显示一条错误消息。以下是代码..
$http({
method: 'POST',
url: 'Link to be called',
data: $.param({
key:Apikey,
id:cpnId
}),
timeout : 5000,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(result){
alert(result);
}).error(function(data){
alert(data);
});
有什么方法可以让我在连接超时时显示用户。 有什么办法可以在一个地方配置它吗?
最佳答案
如果你想在每个请求的连接超时时做一些事情,你可以使用拦截器(全局超时参数不起作用):
// loading for each http request
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($rootScope, $q) {
return {
request: function (config) {
config.timeout = 1000;
return config;
},
responseError: function (rejection) {
switch (rejection.status){
case 408 :
console.log('connection timed out');
break;
}
return $q.reject(rejection);
}
}
})
})
关于javascript - 如何在 Angular js $http 调用中显示超时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27273713/