简体   繁体   中英

Angular HTTP Interceptor does not execute Observable

I am trying to implement a sliding expiry session in Angular, where the session should be extended with every interaction with the API.

The HTTP interceptor is responsible for renewing the token after every response. The problem here is that authService.renewToken() call never really executes the request to the API. I do see begin renew token and renewToken log messages in the console but the token request to the API never fires.

Any ideas what might be the problem here?

AuthenticationService


  public renewToken(token: string): Observable<Token> {

    console.log('renewToken');
    
    return this.api
      .createSession(token)
      .pipe(tap((newToken) => {
          console.log(token === newToken.token);

          this.saveToken(newToken);
        }));
  }
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  private refreshingToken = false;
  private tokenSubject = new Subject<any>();

  constructor(private injector: Injector) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(tap(event => {

      if (this.shouldIntercept(event)) {
        this.tokenSubject.next(null);
        this.refreshingToken = true;

        const authService = this.injector.get(AuthenticationService);

        const currentToken = authService.getToken();

        console.log('begin renew token');
        
        return authService.renewToken(currentToken).pipe(
          switchMap((newToken: Token) => {
            console.log("newToken Recieved:", newToken.token);
            this.tokenSubject.next(newToken);
            return next.handle(req);
          }),
          finalize(() => { this.refreshingToken = false; })
        )
      }

      return next.handle(req);
    }), catchError(errorResponse => {
      this.refreshingToken = false;

      if (errorResponse.status === 401) {
        console.log('Unauthorised response received.');
        this.injector.get(Router).navigate(['error']);
      }
      return throwError(errorResponse);
    }));
  }

Assuming your saveToken function returns an observable, the reason you might not be seeing any API response is that tap won't subscribe to this.saveToken . Try using switchMap / exhaustMap / concatMap (IMO switchMap makes the most sense as it will cancel an in-flight request if a new one arrives). These operators will automatically subscribe to inner observables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM