I'm using Angular HttpInterceptor to handle errors in my Http requests.
If there is an error other than 401, I am displaying a popup modal that contains 2 buttons ('Close' to close the modal and 'Retry' to retry their request again).
However, I am having trouble figuring out how to retry the http call when the user clicks the 'Retry' button. I have confirmed that the console log displays when the user clicks the 'Retry' button, but I'm not sure how to make the http request again. Would I need to clone the request first?
Here is my InterceptorService:
import { Injectable, Inject } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";
import { AuthService } from '@auth0/auth0-angular';
import { DOCUMENT } from '@angular/common';
import Swal from 'sweetalert2'
import { NgxSpinnerService } from 'ngx-spinner';
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(
@Inject(DOCUMENT) private document: Document,
public auth: AuthService,
public spinner: NgxSpinnerService,
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
// logs user out if unauthorized, this works fine.
if (error.status === 401) {
errorMsg = 'Unauthorized';
this.auth.logout({
returnTo: this.document.location.origin
});
} else {
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
Swal.fire({
text: `Error Encountered!`,
confirmButtonText: 'Retry',
confirmButtonColor: '#0f172a',
cancelButtonText: 'Close',
cancelButtonColor: '#f87171',
showConfirmButton: true,
showCancelButton: true
}).then((result) => {
if (result.isConfirmed) {
// I want to retry the http request here. The console log is working fine.
console.log('User has clicked retry button, should retry http request again...');
}
});
}
return throwError(() => error);
})
);
}
Any help is greatly appreciated. Thank you!
How about something like:
and then you can just return in your if statement