Swagat Swain
Swagat Swain

Reputation: 505

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?

Upvotes: 11

Views: 25699

Answers (4)

Prashobh
Prashobh

Reputation: 9542

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

Upvotes: 1

Nicolas Janel
Nicolas Janel

Reputation: 3075

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);
            }
        }
    })
})

Upvotes: 23

Manish Kr. Shukla
Manish Kr. Shukla

Reputation: 4477

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

Upvotes: -2

Phuong Ha
Phuong Ha

Reputation: 31

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.

Upvotes: 1

Related Questions