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 this is I have a base component derived from many components. Now I need to access a service but I don't want to add it to the constructor 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
Yes, ReflectiveInjector.resolveAndCreate()
creates a new and unconnected injector instance.
You can inject Angulars Injector
instance and get the desired instance from it using
constructor(private injector:Injector) {
injector.get(MyService);
}
You also can store the Injector
in some global variable and than use this injector instance to acquire provided instances for example like explained in https://github.com/angular/angular/issues/4112#issuecomment-153811572