简体   繁体   中英

How to implement http post timeout with last Rxjs version?

I used to set a timeout to my angular2 http post like following:

this.http.post('myurl',
      body, {headers: headers})
      .timeout(2000, new Error('Timeout exceeded'))
      .map(res => res.json())
      .subscribe((stuff) => {
         //Do stuff
      }, (errorResponse: any) => {
        //Manage error
      });

But with last version of Rjxs (5.0.1) this isn't valid anymore.

Timeout need an Observable as first parameter and doesn't accept "new Error", how should I do/write that?

Thx you in advance for your help

Note: When I remove the "new Error(...)", my code is then valid but at runtime, I gonna face following error

Error: Uncaught (in promise): TypeError: _this.http.post(...).timeout is not a function TypeError: _this.http.post(...).timeout is not a function

Got it, I had to include following:

import 'rxjs/add/operator/timeout';

this.http.post('myurl',
  body, {headers: headers})
  .timeout(2000)
  .map(res => res.json())
  .subscribe((stuff) => {
     //Do stuff
  }, (errorResponse: any) => {
    //Manage error
  });

****** UPDATE for Angular >= 4.3 and Rxjs >= 5.2.2 ******

With the introduction of RXJS 5.2 the timeout operator could be done using the newly introduced pipe . Furthermore importing it as lettable operators might reduce the bundle size (in case all used operators would be imported as lettable).

Angular 4.3 introduce HttpClientModule which gonna at some point replace HttpModule .

Therefore here the updated code:

import {timeout} from 'rxjs/operators/timeout'; 

let headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type', 'application/json');

let body = {something: 'my_value'};

this.http.post('myurl',
  body, {headers: headers})
  .pipe( 
     timeout(2000)
  )
  .subscribe((stuff: any) => {
     //Do stuff
  }, (errorResponse: HttpErrorResponse) => {
    //Manage error
  });

****** UPDATE for Rxjs >= 6 ******

The above code still works fine in Rxjs v6 but the import or the timeout pipe should be modified like the following:

import {timeout} from 'rxjs/operators';

// same as above

Yes You need to import

import 'rxjs/add/operator/timeout';

Fyi, you have other package to import if you need them

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/timeout';
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM