How to timeout angular2 http request

2019-01-12 02:57发布

问题:

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 dealy/timeout that?

回答1:

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

See this article for more details (with the section "Retry support"):

  • http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/


回答2:

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



回答3:

If you are using RxJS version 6 and above the current syntax is this:

import { timeout } from 'rxjs/operators';

getPeople(){
  return this.http.get(API_URL)
  .pipe(
      timeout(5000) //5 seconds
  );


标签: http angular