Angular Set HTTP Timeout

2019-06-21 20:46发布

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'.

标签: angular http
1条回答
对你真心纯属浪费
2楼-- · 2019-06-21 21:33

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);
      })
    )
查看更多
登录 后发表回答