[英]Angular how to know if a request has timeout more than three times?
I have an Angular 4 app that has a lot of ongoing http request when navigating through the entire app. 我有一个Angular 4应用 ,在整个应用中导航时有很多正在进行的http请求 。
I also want to do something when the http timeout happened three times or more. 我也想在HTTP超时发生三次或更多时执行某些操作。
There are other errors in an http request that might happen but I only want to focus on the timeout error. http请求中可能还会发生其他错误,但我只想关注超时错误。
I have this code below in my http_interceptor . 我的http_interceptor中有以下代码。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const re = '/u/auth/login';
const defaultTimeout = 10000;
if (req.url.search(re) || req.url.search('api.giphy.com/v1') === -1) {
const headers = new HttpHeaders({
Authorization: `Bearer ${localStorage.getItem('token')}`,
// 'Content-Type': 'application/json'
})
const dupReq = req.clone({headers});
const timeOut = Number(req.headers.get('timeout')) || this.defaultTimeout
return next.handle(dupReq).pipe(
timeout(timeOut),
catchError(e => {
return of(null)
})
)
} else {
return next.handle(req)
}
}
How can I handle timeout errors and how can I know that they happened three times or more. 如何处理超时错误,以及如何知道它们发生了3次或以上。 Will I do an increment on each error?
我会增加每个错误的数量吗? and just use a condition to do that function?
并仅使用条件来执行该功能?
As a bonus question how can I also success callback handle to the interceptor? 作为一个额外的问题,我如何也可以成功地对拦截器进行回调处理?
Appreciate if someone could help. 感谢有人可以帮忙。 Thanks in advance.
提前致谢。
chained retryWhen method just above subscribe method.
订阅方法上方的链式retryWhen方法。
import 'rxjs/add/operator/retryWhen';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/scan';
.retryWhen((err)=> {
return err.scan((attempt) => {
if(attempt>5){
throw(err);
}else{
attempt++;
console.log("attempt number "+attempt);
return attempt;
}
},0
).delay(1000)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.