Angular 2 get service by string name

Is there a way to get an instance of an angular 2 injection service only by service name?

For example, in angular 1 you can write:

var service = $injector.get('ServiceName');

and the variable servicewill receive an instance of the service.

I would really appreciate your help!

+4
source share
2 answers

If you specify it by name, you can enter it by name

@NgModule({
  providers: [
      ServiceName, 
      {provide: 'ServiceName', useExisting: ServiceName}
  ],
  ...
+8
source

You can use Explicit Injector Creation using the Injector Class

injector = ReflectiveInjector.resolveAndCreate([ServiceClass, Dependency1Class, Dependency2Class]);

let service= injector.get(ServiceClass); //pass the type not the name
+2
source

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


All Articles