简体   繁体   English

Angular HTTP Interceptor 不执行 Observable

[英]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.我正在尝试在 Angular 中实现一个滑动到期会话,会话应该随着与 API 的每次交互而扩展。

The HTTP interceptor is responsible for renewing the token after every response. HTTP 拦截器负责在每次响应后更新令牌。 The problem here is that authService.renewToken() call never really executes the request to the API.这里的问题是authService.renewToken()调用从未真正执行对 API 的请求。 I do see begin renew token and renewToken log messages in the console but the token request to the API never fires.我确实在控制台中看到了begin renew tokenrenewToken日志消息,但从未触发对 API 的令牌请求。

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 .假设您的saveToken函数返回一个 observable,您可能看不到任何 API 响应的原因是tap不会订阅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).尝试使用switchMap / exhaustMap / concatMap (IMO switchMap最有意义,因为它会在新请求到达时取消switchMap的请求)。 These operators will automatically subscribe to inner observables.这些操作符将自动订阅内部 observable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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