Angular 4 DI:等待方法完成

Angular 4 DI : wait for method completion

为了避免循环依赖,我使用 Injector 注入 AuthService 但是当我 运行 应用程序 Angular 之前执行 intercept() 方法设置 authService 属性 !!!

@Injectable()
export class TokenInterceptorService implements HttpInterceptor{
  private authService;
   constructor(private injector: Injector) {
      setTimeout(() => {
          this.authService = injector.get(AuthService);
console.log('===========================================',this.authService);
        });
      }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${this.authService.getToken()}`
          }
        });

        return next.handle(request);
      }
    }

setTimeout 不应用于避免循环依赖,因为它会导致像这样的竞争条件。

避免循环依赖的正确方法是就地检索它们。在拦截器 class 的情况下,它是 intercept 方法:

export class TokenInterceptorService implements HttpInterceptor {
  constructor(private injector: Injector) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authService = this.injector.get(AuthService);
    ...
  }
}

如果有可能在由导致循环依赖的服务执行的请求中使用拦截器(AuthService),则应向拦截器添加额外的保护措施以避免递归。