角度设置HTTP超时 [英] Angular Set HTTP Timeout
问题描述
我一直在寻找一种方法来停止/终止一个超过一定时间的http请求. 因此,在Angular 5中,是否仍然需要为http请求设置超时?
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?
此问题中列出的方法
如何为angular2 + http请求实施超时会出现错误:
错误TS2339:可观察"类型不存在属性超时".
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())
.
赞:
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);
})
)
这篇关于角度设置HTTP超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!