Angular 2 get service by string name
Asked Answered
D

2

8

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!

Defence answered 4/1, 2017 at 18:49 Comment(0)
A
12

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

@NgModule({
  providers: [
      ServiceName, 
      {provide: 'ServiceName', useExisting: ServiceName}
  ],
  ...
Axe answered 4/1, 2017 at 19:3 Comment(10)
How would I go about getting this service from a component? Using Injector.get is deprecated as of version 4Kolk
"Injector.get(token: any, notFoundValue?: any): any is now deprecated use the same method which is now overloaded as Injector.get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T): T;" github.com/angular/angular/blob/master/…Jamshedpur
Thanks for the info, but how would this be used in a component? I'm trying to upgrade the code from this answer to the 'new' format, but I can't wrap my head around the whole InjectionToken thingKolk
InjectionToken is just a key used to register a provider with and then to request an instance for this key with .get(...).Jamshedpur
How would I get the key if it's passed as a string variable from a template? Example of what I mean (check out hello.component.ts)Kolk
I see what you mean. Should work as explained in angular.io/api/core/InjectionToken#description.Jamshedpur
Let us continue this discussion in chat.Kolk
I'd suggest you create a new question. I'm quite out of practice with Angular.Jamshedpur
downvoting answer, as it's incomplete - does not show how to access such service, only how to define name for a service.Abalone
@MaciejMiklas that's shown in the question.Jamshedpur
N
1

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
Network answered 4/1, 2017 at 19:5 Comment(3)
That wasn't what the OP asked.Pentagram
It's another option! I haven't contribute with stackoverflow anymore because of this kind of behavior. Options should be given.Network
Unfortunately, this is not an option. The question clearly asks "just by the service name?", so offering a solution that just ignores that restriction is not helpful.Unrestraint

© 2022 - 2024 — McMap. All rights reserved.