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?

Angular doesn’t implement xhr.ontimeout in the $httpBackend… So it is not handled by angular at all at this moment.

You could try this method:

var startTime = new Date().getTime();
$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, status, header, config){
       alert(result);
    }).error(function((result, status, header, config){
        var respTime = new Date().getTime() - startTime;
        if(respTime >= config.timeout){
            //time out handeling
            alert('time out');
        } else{
            //other error hanndling
            alert(result);
        }
    });

Sorry for the terrible indentation

2 Likes

you can put your error message in the error section, because when you timeout is over will enter in the error section :slight_smile: sorry for my bad english