Getting instance of service without constructor injection
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);
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