0

I'm trying to create an interceptor which should call a function to refresh the session when a 401 error is returned. This is what I have so far but it won't build and I can't work out how to do this:

intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
  withCredentials: true
});
return next.handle(request).pipe(
  catchError((error: HttpErrorResponse) => {
    if (error.status === 401) {
      return this.userAPI
        .refreshSession(this.authService.getRefreshToken())
        .then(res => {
          this.authService.setAuthenticated(false);
          return next.handle(request);
        });
    } else {
      this.authService.setAuthenticated(false);
    }
  })
 );
}

VS Code reports:

Type 'Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | Observable<HttpEvent<any>>>' is not assignable to type 'Observable<HttpEvent<any>>'.

1 Answer 1

1

catchError must return an observable. Try below or something similar:

intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
  withCredentials: true
});
return next.handle(request).pipe(
  catchError((error: HttpErrorResponse) => {
    if (error.status === 401) {
      return this.userAPI
        .refreshSession(this.authService.getRefreshToken())
        .then(res => {
          this.authService.setAuthenticated(false);
          return next.handle(request);
        });
    } else {
      this.authService.setAuthenticated(false);
      // Add this
      return next.handle(request);
    }
  })
 );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.