我正在尋找一種可能性來重復/遞回呼叫 catchError 以進行 http 呼叫。首先我只是使用retry(x),但現在我需要修改請求以防出錯。
現在catchError只呼叫一次(當然)。如何修改它?
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let attempts = 0;
return next.handle(request).pipe(
catchError(e => {
attempts ;
if (attempts < 5) { return next.handle(request.clone({ ...{} })); }
throw e;
})
);
}
}
uj5u.com熱心網友回復:
因此,如果您只需要第一次修改,只需將重試放在修改后的 observable 內catchError:
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => {
return next.handle(request.clone({ ...{} })).pipe(retry(4));
})
);
}
}
如果您每次都需要修改,遞回錯誤處理程式將執行此操作:
export class HttpErrorInterceptor implements HttpInterceptor {
private handleError(request: HttpRequest<any>, next: HttpHandler, error, attempts: number) {
return next.handle(request.clone({ ...{} })).pipe(
catchError(e => (attempts < 5) ? this.handleError(request, next, e, attempts 1) : throwError(e))
)
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => this.handleError(request, next, e, request, 1))
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454276.html
上一篇:Firebase不保存空陣列
