Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 766
David Dal Busco Avatar asked Dec 25 '16 09:12

David Dal Busco


1 Answers

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
like image 159
David Dal Busco Avatar answered Oct 13 '22 02:10

David Dal Busco