Javascript 如何在 angular js $http 调用中显示超时错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27273713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display timeout error in angular js $http calls?
提问by Swagat Swain
I am making an ajax call using $http in angular js. I have implemented timeout in it. But I want to show the user an error message if the connection times out. The following is the code..
我正在 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);
});
Is there any way so that I can display the user if the connection is timed out. Is there any way so that it can be configured at one place?
如果连接超时,有什么方法可以显示用户。有没有办法让它可以在一个地方配置?
回答by Nicolas Janel
And if you want to do someting when connection timed out for every request, you can use interceptors (global timeout param doesn't work) :
如果你想在每个请求的连接超时时做一些事情,你可以使用拦截器(全局超时参数不起作用):
// 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);
}
}
})
})
回答by Phuong Ha
Have a try on this blog page: http://www.jonhartmann.com/index.cfm/2014/7/23/jsFiddle-Example-Proper-Timeout-Handling-with-AngularJSIt has a complete angular running example which resolve your question.
试试这个博客页面:http: //www.jonhartmann.com/index.cfm/2014/7/23/jsFiddle-Example-Proper-Timeout-Handling-with-AngularJS它有一个完整的角度运行示例,可以解决你的问题。
回答by Prashobh
You can use angular interceptor to achieve this.
您可以使用角度拦截器来实现这一点。
$httpProvider.responseInterceptors
.push(['$q', '$injector','$rootScope', function ( $q, $injector,$rootScope) {
return function (promise) {
return promise.then(function (response) {
return response;
}, function (response) {
console.log(response); // response status
return $q.reject(response);
});
};
}]);
}]);

