Angular DI (injector.get(FooService))

Viewed 106

I have just started reading some code from somewhere else and I have to understand it. I have read a lot in Angular website and some other coding related websites but I have not undersoot the following section yet and need your help.

export class AppComponent {
  w: FooService;
  constructor(private injector: Injector) {
    if (environment.production) {
      this.w = this.injector.get(FooService);
    }
  }
}

I do not understand why the developer has injected the FooService in such a way, and why didn't he implemented the injection like bellow:

export class AppComponent {
  constructor(w: FooService) {
  }
}

And finally, would you please explain the main goal of this.injector.get()?

1 Answers

Injector can be used to dynamicaly(programaticaly) register or load a service.

Check the following example from official documentation

Angular Injection Token doc

Also another example of how to manualy register and inject a service in a Test again from official documentation

Angular Manually Inject Service

There is also another answer in SO with a specific use case for injector. An Angular Service that has 2 different implementations and some component that uses that service must choose dynamically an implementation for that service. This would be a good example to understand conditional injection that is reffered from Beshambher Chaukhwan in comments.

another relevant answer in SO

Related