I have a @Injectable
service defined in bootstrap. I want to get the instance of the service without using constructor injection. I tried using ReflectiveInjector.resolveAndCreate
but that seem to create a new instance.
The reason I'm trying to do is I have a base component derived by many components. Now I need to access a service but I don't want to add it to the ctor because I don't want to inject the service on all of the derivative components.
TLDR: I need a ServiceLocator.GetInstance<T>()
UPDATE: Updated code for RC5+: Storing injector instance for use in components
Just use the getter this. aService . They only time this won't work is if you are trying to use AService within the constructor of Bservice , then you would have the same issue of a circular reference since Aservice would not be ready yet. By using the getter you are deferring injecting the service until you need it.
If you want to use angular services (and Http is an angular service) you must inject them as I told above as a constructor attribute to another service / component , which means if you want to use Http you need to have your service injectable. So the answer is no, you can't do it in a nice way.
The bottom line is: you don't have to forego dependency injection. You can define & implement interfaces in different layers.
If no Angular decorator has been used on a class there is no way for Angular to read what dependencies it requires. This is why we need to use @Injectable() . If our service injects providers we must add @Injectable() , which providers no extra functionality, to tell Angular to store that metadata it needs.
In the updated Angular where ngModules are used, you can create a variable available anywhere in the code:
Add this code in app.module.ts
import { Injector, NgModule } from '@angular/core'; export let AppInjector: Injector; export class AppModule { constructor(private injector: Injector) { AppInjector = this.injector; } }
Now, you can use the AppInjector
to find any service in anywhere of your code.
import {AppInjector} from '../app.module'; const myService = AppInjector.get(MyService);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With