Angular 4 DI:等待方法完成

时间:2017-11-08 14:31:43

标签: angular angular4-httpclient angular-di

为了避免循环依赖,我使用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);
      }
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

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

避免循环依赖的正确方法是就地检索它们。在拦截器类的情况下,它是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)执行的请求中有可能使用拦截器,则应该在拦截器中添加额外的安全措施以避免递归。