Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement timeout for angular2+ http request

Tags:

Here is just regular request looking like that:

this.people = http.get('http://localhost:3000/users')                   .map(response => response.json()); 

Is there any way to delay/timeout that?

like image 304
sreginogemoh Avatar asked Apr 19 '16 12:04

sreginogemoh


People also ask

What is the default timeout for HTTP request in angular?

In complement to the other answers, just beware that if you use the proxy config on the dev machine, the proxy's default timeout is 120 seconds (2 minutes).

What is http timeout?

The HyperText Transfer Protocol (HTTP) 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client.


Video Answer


2 Answers

You can leverage the timeout operator of observables, as described below:

return this.http.get('http://api.geonames.org/postalCodeSearchJSON',           { search: params })     .retryWhen(error => error.delay(500))     .timeout(2000, new Error('delay exceeded')) // <------     .map(res => res.json().postalCodes); 
like image 134
Thierry Templier Avatar answered Oct 12 '22 09:10

Thierry Templier


The return value of http.get() is an observable, not the response. You can use it like:

getPeople() {   return http.get('http://localhost:3000/users')       .timeout(2000)       .map(response => response.json());   } }  foo() {   this.subscription = getPeople.subscribe(data => this.people = data) }  // to cancel manually cancel() {   this.subscription.unsubscribe(); } 

See also https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md

like image 26
Günter Zöchbauer Avatar answered Oct 12 '22 09:10

Günter Zöchbauer