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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With