Angular 5 HttpInterceptor 重试请求 [英] Angular 5 HttpInterceptor Retry Request
问题描述
Angluar 5 HttpInterceptor 如何在出错时重试请求?
How can an Angluar 5 HttpInterceptor retry a request on error?
Angular 文档没有显示 HttpInterceptor 重试的示例:https://angular.io/guide/httphttps://angular.io/api/common/http/HttpInterceptor
The Angular docs don't show an example of an HttpInterceptor retry: https://angular.io/guide/http https://angular.io/api/common/http/HttpInterceptor
请注意,对 HttpClient 对象进行了重试.这在这种情况下没有帮助.
Note that there is a retry on the HttpClient object. This is NOT helpful in this case.
我试图实现的伪逻辑:发送请求IF 错误响应 THEN 更改请求并重试请求.
Psuedo logic I'm trying to achieve: Send request IF error response THEN change the request and retry the request.
此 HttpInterceptor 成功运行请求并捕获错误但不重试请求.
This HttpInterceptor successfully runs the request and catches the error but doesn't retry the request.
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.do(event => {
}, (err: any) => {
let reqRepeat = req.clone(); // For now, keep it simple. Don't change original request.
return next.handle(req); // Retry request. THIS DOESN'T SEEM TO DO ANYTHING!
})
}
};
推荐答案
rxjs 'do' 操作符不会修改观察者.返回 'next.handle(...)' 不应该工作.
The rxjs 'do' operator does not modify the observer. Returning the 'next.handle(...)' should not work.
尝试改用catch"运算符.
Try to use the 'catch' operator instead.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catch(() => {
const newReq = req.clone();
return next.handle(newReq);
});
}
不要忘记导入 catch 操作符:
Do not forget to import the catch operator:
import 'rxjs/add/operator/catch';
这篇关于Angular 5 HttpInterceptor 重试请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!