在 Angular 拦截器中使用 retry with delay 操作符时,可能会遇到从服务器返回多个响应的意外情况。这是因为 retry 操作符会重新订阅可观察对象,并向服务器发送新请求。为解决这个问题,我们可以使用 catchError 操作符来捕获错误并手动处理它们。
以下是一个示例 interceptor,使用 retry with delay 和 catchError:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retryWhen, delay, take, mergeMap, catchError } from 'rxjs/operators';
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
retryWhen(errors =>
errors.pipe(
// 尝试五次,每次间隔 1 秒钟
delay(1000),
take(5),
mergeMap(error => throwError(error))
)
),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// TODO: 处理未授权错误
}
return throwError(error);
})
);
}
}
该示例将在发送服务器请求失败 5 次后抛出错误,并使用 catchError 操作符捕获该错误并处理它。如果错误的 HTTP 状态码为 401,则可以在 catchError 中执行自定义未授权错误的处理代码。