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?
This article will deal with the ‘$timeout’ service of AngularJS. This ‘$timeout’ service of AngularJS is functionally similar to the ‘window.setTimeout’ object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
http/https use socket.setTimeout() whose timer is restarted in stages of socket lifecycle. It doesn't ensure a timeout for the overall request & response. If you want to make sure that a request completes in a specific time or fails, you need to prepare your own timeout solution.
Let's start with the standard library of Node.js. http and https packages provide request () function, which makes a HTTP (S) request. http.request () takes a timeout option. Its documentation says: timeout <number>: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.
If you need to handle errors in only one place, you can use catch and return a default value (or empty response) instead of failing completely. You also don't need the .map just to cast, you can use a generic function. Source: Angular.io - Getting Error Details.
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);
}
}
})
})
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.
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);
});
};
}]);
}]);
More info see this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With