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..
$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?
Have a try on this blog page: http://www.jonhartmann.com/index.cfm/2014/7/23/jsFiddle-Example-Proper-Timeout-Handling-with-AngularJS It has a complete angular running example which resolve your question.
Set a global timeout by configuring the $httpProvider:
angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
});
You just need to check the response status and that's it :
}).error(function(data, status, header, config) {
if (status === 408) {
console.log("Error - " + status + ", Response Timeout.");
}
});
For global HTTP timeout, take a look at this answer