我尝试使用 Angulars HttpClient 服务,通过多次尝试和延迟来发出请求。代码有效,但我注意到在devTools网络中,最后发送和取消了一个额外的请求。我在做错的是代码:
return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
retryWhen(errors => {
return errors.pipe(
mergeMap((er: any) => {
if (er.status === 504 || er.status === 503) {
return of(er.status).pipe(delay(1000));
}
return _throw({message: er.error.message || 'Notification.Core.loginError'});
}),
take(3),
concat(_throw({message: 'Notification.Core.networkError'}))
);
})
);
答案 0 :(得分:3)
以下是我如何解决它。现在有三次尝试,每次请求都有第二次延迟,没有额外的取消请求
return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
retryWhen(errors => errors.pipe(
switchMap((error) => {
if (error.status === 504 || error.status === 503) {
return of(error.status);
}
return _throw({message: error.error.message || 'Notification.Core.loginError'});
}),
scan(acc => acc + 1, 0),
takeWhile(acc => acc < 3),
delay(1000),
concat(_throw({message: 'Notification.Core.networkError'}))
))
);
答案 1 :(得分:1)
下面是我的 HttpInterceptorService 代码。 代码工作正常,除外。我想根据计数重试。 假设我最初的 retryWaitMilliSeconds = 300 和 retryCount = 3
第一次我想用 300 * 1 重试
第二次我想用 300 * 2 重试
第三次我想用 300 * 3 重试
private retryCount = 3;
private retryWaitMilliSeconds = 500;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let ok: string;
const started = Date.now();
// Handle request
request = request.clone({
setHeaders: {
"Authorization": "Bearer XXXXXXXXXXXXXXXXXXX"
}
});
return next.handle(request).pipe(
tap(event => ok = event instanceof HttpResponse ? 'succeeded' : ''),
retryWhen(error => error.pipe(concatMap((error, count) => {
ok = 'failed'
if (count <= this.retryCount && error.status === 500) {
return of(error);
}
return throwError(error);
}), delay(this.retryWaitMilliSeconds),
tap(err => console.log("Retrying...")))
), finalize(() => {
}))
}