Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine request time out in angular $http

Tags:

angularjs

I am sending an http request using angular as below.

$http({
    url: url,
    params: params,
    method:'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    timeout: 60000    //60 seconds
}).success(function(data, status, headers, config) {
    //do something 
}).error(function(data, status, header, config) {
    if(timedout){  //determine occurrence of timeout.
        //invoke timeout handler
    } else  
        //handle other error
    }
});

How can I determine the timeout?

I have observed that status code "0" is received in this case. Is it safe to check status==0 for timeout?

Please note that I am not asking about HTTP Request timeout (status code 408).

like image 764
Bilal Mirza Avatar asked Jul 26 '13 05:07

Bilal Mirza


People also ask

What is the default timeout for HTTP request in angular?

The default value is 100,000 milliseconds (100 seconds).

How do I set HTTP request timeout?

Timeouts on 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.

What is the max timeout for HTTP request?

The default time out value is 30 seconds. Thus, by default, the server will close the connection if idle for more than 30 seconds. The maximum value for this parameter is 300 seconds (5 minutes).

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.


3 Answers

I have done it as below...

var startTime = new Date().getTime();
$http.post(...)
    .success(function(resp, status, header, config) {...})
    .error(function(resp, status, header, config) {
        var respTime = new Date().getTime() - startTime;
        if(respTime >= config.timeout){
            //time out handeling
        } else{
            //other error hanndling
        }
    });
like image 140
Bilal Mirza Avatar answered Oct 23 '22 01:10

Bilal Mirza


I just read through the source code. In the source code of the $httpBackend, the xhr.ontimeout is not being handled. They should implement xhr.ontimeout.

Unfortunately Angularjs doesn't support the http timeout handling for right now. :(

like image 39
zs2020 Avatar answered Oct 23 '22 01:10

zs2020


According to Angular's documentation, the timeout parameter is expressed in milliseconds.

So you're setting it at 1 milliseconds, which is extremely low. This will probably make the request fail in 99.9999 % of situations.

like image 2
Radu Murzea Avatar answered Oct 23 '22 02:10

Radu Murzea