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
             ){}
6
  • Not use HttpClient in your interceptor. Use a service. Then inject the service in the CustomHttpInterceptor using Injector like stackoverflow.com/questions/47417899/… Commented Dec 3, 2017 at 14:11
  • Worked, btw why this solution works and mine not? Commented Dec 3, 2017 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 Commented Dec 3, 2017 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? Commented Dec 3, 2017 at 15:03
  • 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. Commented Jan 9, 2018 at 11:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.