Search code examples
angularangular4-httpclientangular-di

Angular 4 DI : wait for method completion


To avoid cyclic dependency i am using the Injector to inject the AuthService but when i run the application Angular execute the intercept() method before setting the authService property !!!

@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


Solution

  • setTimeout shouldn't be used to avoid cyclic dependencies because it results in race conditions like this one.

    The proper recipe to avoid cyclic dependencies is to retrieve them in-place. In case of interceptor class it is intercept method:

    export class TokenInterceptorService implements HttpInterceptor {
      constructor(private injector: Injector) {}
    
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authService = this.injector.get(AuthService);
        ...
      }
    }
    

    If there is a chance that interceptor is used in requests that are performed by a service that causes cyclic dependency (AuthService), additional safeguards should be added to the interceptor to avoid recursion.