如果Angular中的httpClient超时,则调用一个函数 [英] call a function in case of httpClient timeout in Angular
问题描述
我有一个功能,可以在服务器上发送一些超时请求,每个请求都像这样:
I have a function sending a few requests on the server with a timeout each like:
this.httpClient.get(url, { headers: headers })
.timeout(30000)
.subscribe(
(response) => {
...
},
error => {
...
}
...
);
在超时(30秒)的情况下,每个请求都被取消,这是可以理解的. 我的问题是,在超时的情况下,已取消的请求不会被视为错误,因此它不会转到请求的错误部分. 在这种情况下可以调用函数吗?
In case of timeout (30s), everyone request gets canceled, which is understandable. My problem is, that in case of a timeout, the canceled request is not seen as an error, so it doesn't go to the error-part of the request. Are there any possibilities to call a function in this case?
推荐答案
如果您使用的是Angular 6,则超时处理的方式为pipe/timeout
,请查看以下示例:
If you are using Angular 6, the way to go with the timeout handling is pipe/timeout
, please look at this example:
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;
})
This fragment is from this example I wrote to demonstrate HTTP Interceptors: https://stackblitz.com/edit/angular-my-http-interceptor?file=src%2Fapp%2Fapp.component.ts
这篇关于如果Angular中的httpClient超时,则调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!