I was looking for a way to stop/terminate an http request if it exceeds a certain time.
So in Angular 5, is there anyway to set a timeout for an http request?
If there is a way, how can we do something, like execute some function, after a timeout?
The method listed in this question
How to timeout angular2 http request
gives an error:
error TS2339: Property 'timeout' does not exist on type 'Observable'.
Just as the comment mentioned, you need to use the timeout
operator. However, the linked answer is a little bit outdated. Since rxjs 5.5.2 you need to use the pipe
method with lettable
operators. And assumming you are using the HttpClient
to make your requests, there is no need for map(response => response.json())
.
Like this:
import { timeout, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
http.get('https://example.com')
.pipe(
timeout(2000),
catchError(e => {
// do something on a timeout
return of(null);
})
)