Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 get service by string name

Is there a way get an instance of an injectable service of angular 2 just by the service name?

For Example, in Angular 1 you could write:

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

and the service variable would get an instance of the service.

I'd really appreciate your help guys!

like image 445
Ron Avraham Avatar asked Jan 04 '17 18:01

Ron Avraham


2 Answers

If you provide it by name, you can inject it by name

@NgModule({
  providers: [
      ServiceName, 
      {provide: 'ServiceName', useExisting: ServiceName}
  ],
  ...
like image 119
Günter Zöchbauer Avatar answered Sep 18 '22 11:09

Günter Zöchbauer


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
like image 39
Fals Avatar answered Sep 19 '22 11:09

Fals