Injector Error "Vendor Analysis Errors: Unable to create a circular dependency!"

I tried creating an HttpInterceptor to add some authorization headers to every http that happens. I need to get the headers from the AuthService . Here is the code below:

interceptor:

import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { AuthService } from './auth.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) { } } 

AuthService:

 import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class AuthService { constructor(private http: HttpClient) { } } 

AppModule:

 providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, AuthService] 

I get the following error:

Error: Provider Analysis Errors: Unable to create circular dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR β†’]"): in NgModule AppModule in./ AppModule@-1 : -1

I already checked the previous answers, but I don’t understand where the cyclic dependency was discovered. What I'm trying to do is described here: https://angular.io/guide/http#setting-new-headers

+5
source share
2 answers

Look at the GitHub Discussion (Issue No. 18224)

As a workaround, you can use Injector manually and enter the appropriate service inside the intercept method: https://github.com/angular/angular/issues/18224#issuecomment-316957213

I decided not to install authService in the constructor, but in the interception function.

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Get the auth header from the service. const auth = this.inj.get(AuthenticationService); const authToken = auth.getAuthorizationToken(); ... } 

UPDATE:

Prior to Angular 4.3.0 , unfortunately, it was not possible to use Injector manually inside the intercept method:

ERROR Error: Uncaught (in promise): RangeError: Maximum call stack size exceeded

So there is another workaround using rxjs :

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return Observable.create((observer: any) => { setTimeout(() => { const authService = this.injector.get(AuthenticationService) observer.next(authService.getAuthorizationHeader()) observer.complete() }) }) .mergeMap((Authorization: string) => { let authReq = req if (Authorization) { authReq = req.clone({ setHeaders: { Authorization } }) } return next.handle(authReq) }) } 
+9
source

Remove the list of AuthService services from the list of providers, since it is imported into the Interceptor, and therefore a circular dependency.

+2
source

Source: https://habr.com/ru/post/1270820/


All Articles