2

How can I inject http client into HTTP Interceptor? Whenever I do it, it throws: Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

My interceptor looks like:

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

  constructor(private ehs: ErrorHandlerService,
              private localStorageService: LocalStorageService,
              private router: Router,
              private http: HttpClient
             ){}
Jan Testowy
  • 649
  • 3
  • 13
  • 32
  • Not use HttpClient in your interceptor. Use a service. Then inject the service in the CustomHttpInterceptor using Injector like https://stackoverflow.com/questions/47417899/angular-4-and-oauth-intercept-401-responses-refresh-the-access-token-and-retr/47420967#47420967 – Eliseo Dec 03 '17 at 14:11
  • Worked, btw why this solution works and mine not? – Jan Testowy Dec 03 '17 at 14:56
  • I don't know if you can inject HttpClient as const http = this.inj.get(HttpClient);.(I didn't try it) It's only that I like a interceptor with less code possible – Eliseo Dec 03 '17 at 15:00
  • Yes but ex you can’t inject a service with HttpClient in it to the Http interceptor. It throws exactly the same errors like I provided in question. Why? – Jan Testowy Dec 03 '17 at 15:03
  • Yes, the only way it's using Injector. I think it's a problem when the .ts transpile to javascript. We need known the dependency and if inject the service in the constructor it's happen a cycling dependency, but it's a personal opinion – Eliseo Dec 03 '17 at 15:20
  • 2
    During DI HttpClient instances are built something like this: `new HttpClient(arrayOfHttpInterceptors)`. When you try to inject the HttpClient into one of the interceptors it can't work, because both client and interceptor would have to wait for the other one to be built first. However, you can get either during runtime through the injector, because they do not mutually depend on each other during instantiation. – j2L4e Jan 09 '18 at 11:02

1 Answers1

2

Uou can use Injector

  constructor(inj: Injector) {
    this.auth = inj.get(AuthService)
  }

See this example: https://plnkr.co/edit/8CpyAUSJcCiRqdZmuvt9?p=preview

https://angular.io/api/core/Injector

Long discution about this issue here: https://github.com/angular/angular/issues/18224

Clayton K. N. Passos
  • 1,292
  • 12
  • 15