Is there a way to find from where Angular is injecting a value?

Viewed 284

I know that in Angular there is a hierarchical dependency injection model with injectors at root and component level. Is there a way to find from where Angular is injecting a value? I am facing an issue. A wrong class is being injected in my application. I need to debug how Angular is resolving the dependency.

1 Answers

If you think that the wrong class is being injected, then you may have a misconfigured module structure where some child injector (provider) is providing a different class to your Component.

You may want to look at the Angular.io Dependency Injection Documentation page. Specifically the part on Injector Hierarchy and Service Instances.

If you want to manually configure the provider(s) of your Service, then you can declare explicitly where the class is provided by using the providedIn property of the @Injectable annotation:

@Injectable({
  providedIn: 'root', // or `providedIn: MyModule,`
})
export class MyService {
  constructor() { }
}

Or you could set the provider for your Service in the module in which you will inject the Service, like so:

providers: [
  { provide: MyService, useClass: MyServiceAltImplementation }
]
Related