I am calling an API to get random details. The problem is that, sometimes I am getting 502 error as bad gateway and it may also break due to a bad network connection also. Below is my code to API call
// COMPONENT API CALL SUBSCRIBE
this._service.post('randomAPI/getdetails', filters).subscribe((response: any) => {
this.itemList = response;
});
// SHARED SERVICE
post<T>(url: string, body: any): Observable<T> {
return this.httpClient.post<T>(url, body);
}
Whenever I get 500 or 502 server error, using an Interceptor I am routing to a error page to notify the user as server issue.
Instead, can I make the API to try one more time in component level or interceptor level if it fails and then route to error page?
// INTERCEPTOR
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => {
if (error.status === 401 || error.status === 400 || error.status === 403) {
this.router.navigateByUrl('abort-access', { replaceUrl: true });
} else if (error.status === 500 || error.status === 502) {
this.router.navigateByUrl('server-error', { replaceUrl: true });
}
return throwError("error occured");
}));
}
I saw few examples as they are using pipe and adding retryWhen() to achieve this. But as I am very new to angular, I am not able to figure out a way to do it.
Could anyone please help?