Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 462
SEY_91 Avatar asked Apr 10 '26 18:04

SEY_91


1 Answers

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.

like image 86
Estus Flask Avatar answered Apr 12 '26 11:04

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!