我如何 get/use 在 AuthInterceptor class 中访问令牌 Angular 8

How can i get/use accessToken in AuthInterceptor class in Angular 8

我如何 get/use AuthInterceptor class 中的 accessToken 并将其添加到每个 API (.NetCore) 调用中。 我已经实现了

 getAccessToken() {
    return Auth.currentSession().then(res => {
      return res.getAccessToken().getJwtToken();
    });
  }

在 authService 中,但我似乎无法在 intercept(req: HttpRequest, next: HttpHandler){} 方法中使用它。我可以实施任何解决方法或流程更改。

首先,将您的承诺转换为 Observable 到您的 AuthService.ts

import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';

...

getAccessToken(): Observable<string> {
  return from(Auth.currentSession()).pipe(
    switchMap(session => from(session.getAccessToken().getJwtToken())
  )
};

然后您就可以轻松地将它用于您的 AuthHttpInterceptor :

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  constructor(
    private authService: AuthService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.authService.getAccessToken().pipe(
      switchMap(jwtToken => {
        // clone the request to add the new header.
        const authReq = req.clone({ 
          headers: req.headers.set('Authorization', `Bearer ${jwtToken}`) 
        });
        return next.handle(authReq);
      })
    );
  }
}