3

为了避免循环依赖,我使用Injector注入AuthService但是当我运行应用程序 Angularintercept()在设置属性之前执行该方法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);
      }
    }

在此处输入图像描述

4

1 回答 1

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) 的请求中使用拦截器,则应向拦截器添加额外的保护措施以避免递归。

于 2017-11-08T14:56:22.987 回答