Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display timeout error in angular js $http calls?

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?

like image 325
Swagat Swain Avatar asked Dec 03 '14 14:12

Swagat Swain


People also ask

What is the ‘$ timeout’ service of AngularJS?

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.

How do I set a timeout for a HTTP request?

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.

How to set socket timeout in Node JS?

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.

How do you handle errors in angular?

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.


3 Answers

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);
            }
        }
    })
})
like image 149
Nicolas Janel Avatar answered Oct 19 '22 04:10

Nicolas Janel


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.

like image 32
Phuong Ha Avatar answered Oct 19 '22 03:10

Phuong Ha


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

like image 34
Prashobh Avatar answered Oct 19 '22 03:10

Prashobh