Am trying to use the Angulars HttpClient service to make a request with a number of tries and a delay in between. The code works, but i noticed in the devTools network tap that in the end an extra request is sent and canceled. What am I doing wrong here is the code:
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'}))
);
})
);
Here is an Image of Firefox and Chrome network tab, there should be three request but its making four and canceling the last one
Here is how I solved it. now three tries with a second delay per request and no extra canceled request
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'}))
))
);
Below is my HttpInterceptorService Code. Code is working fine as excepted. I would like to retry based on count. Let say my initial retryWaitMilliSeconds = 300 and retryCount = 3
First time I want to retry with 300 * 1
Second time I want to retry with 300 * 2
Third time I want to retry with 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(() => {
}))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.