My goal is to intercept responses returning from the /api
, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occurs).
In the code below, I believe I am triggering the request using the http handler, subscribing to its events, and handling the case where it fails on a 401 error by refreshing the session and returning an observable of the cloned request being processed by the handler.
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!request.url.startsWith('/api')) {
return next.handle(request)
}
const cloned = request.clone()
return next.handle(request)
.pipe(
catchError((error: any) => {
if (error.status !== 401) {
return throwError(error)
}
return from(this.sessionService.refresh())
.pipe(map(() => next.handle(cloned)))
})
)
}
Do you have any suggestions on how I can achieve my objective?