让前端飞前端学习之路

在Angular中httpClient怎么设置超时时间

2019-11-15  本文已影响0人  itming

在angular发送请求中,如果请求的时间太长,用户体验就会不好,比如前端调接口的时候,界面会显示“加载中”,如果请求过长界面就会一直显示“加载中”,当然后端是可以设置超时时间的,过了多少秒,就算连接断开的。
其实angular前端也可以去设置这个超时时间,用timeout(5000)来设置超时时间。

this.httpClient.get(url, { headers: headers })
        .timeout(30000)
        .subscribe(
            (response) => {
                ...
            },
            error => {
                ...
            }
                ...
            );

如果超时(30秒),每个请求都会被取消。它会走error里的处理代码的。
如果是angular6的话,超时处理的方法是pipe/timeout
示例:

this.http.get('https://httpstat.us/200?sleep=5000')
  .pipe(timeout(1000))
  .subscribe(response => {
    console.log('forceTimeout', response);
  }, (error) => {
    console.log('Error', error);
    this.error = error.constructor.name;
  })
上一篇 下一篇

猜你喜欢

热点阅读