How to Retry http requests in Angular Interceptor ONLY when user clicks a button #7175
-
Hi all, I'm new to Angular & RxJS. I'm using Angular HttpInterceptor to handle errors in my Http requests. If there are any errors other than a 401, I am displaying a popup modal that contains 2 buttons ('Close' to close the modal and 'Try Again' to retry their request again). However, I am having trouble figuring out how to use RxJS's Retry method to retry the http call ONLY when the user clicks the 'Try Again' button in the popup modal. I have confirmed that the console log displays when the user clicks the 'Try Again' button, but I'm not sure why it isn't making/retrying the http request again. My assumption is that clicking the 'Try Again' button is an asynchronous event, but I'm not sure if RxJS has a recommended way to handle this desired use case. Here is my InterceptorService:
Any help is greatly appreciated. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The Also, the This should work: intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request)
.pipe(
retry({ delay: (error: HttpErrorResponse) => {
// Code for the popup modal
// We can just return the promise that Swal.fire emits - When it resolves we can either rethrow the error
// (so it cascades further down), or resolve the promise (then `retry` will perform the retry)
return Swal.fire({
text: 'Error Encountered.',
confirmButtonText: 'Close',
confirmButtonColor: '#0f172a'
}).then((result) => {
if (result.isConfirmed) {
// This console log works
console.log('USER WANTS TO RETRY THEIR REQUEST!!!');
return true;
} else {
throw error; // Cascade it down
}
});
} }),
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.status === 401) {
errorMsg = 'Unauthorized';
this.auth.logout({
returnTo: this.document.location.origin
});
} else {
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
return throwError(() => error);
})
);
} |
Beta Was this translation helpful? Give feedback.
The
retry
operator receives anObservableInput
(an observable or anything that can transform into an observable) on thedelay
function, that tells it when to retry it.Also, the
throw 'Error thrown!!!
shouldn't be there. This is just killing the operator. Is there a reason you wanted to throw something in there?This should work: