角度设置HTTP超时

时间:2018-04-12 08:05:17

标签: angular http

我正在寻找一种方法来停止/终止http请求超过一定时间。 那么在Angular 5中,无论如何都要为http请求设置超时?

如果有办法,我们怎么能在超时后做一些事情,比如执行某些功能?

此问题中列出的方法

How to timeout angular2 http request 给出错误:

  

错误TS2339:类型'Observable'上不存在属性'timeout'。

1 个答案:

答案 0 :(得分:10)

正如评论所述,您需要使用timeout运算符。但是,链接的答案有点过时了。从rxjs 5.5.2起,您需要将pipe方法与lettable运算符一起使用。并且假设您使用HttpClient发出请求,则无需map(response => response.json())

像这样:

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);
      })
    )
相关问题