Suppose I have an Angular 2 component-directive, where I want the injected dependency that the component uses to be determined by an @Input().
I want to write someth
In general, same approach is described in Angular2 documentation: InjectorComponent
@Component({
providers: [Car, Engine, Tires, heroServiceProvider, Logger]
})
export class InjectorComponent {
car: Car = this.injector.get(Car);
heroService: HeroService = this.injector.get(HeroService);
hero: Hero = this.heroService.getHeroes()[0];
constructor(private injector: Injector) { }
}
You must inject Injector
in constructor and list all services in providers
property of @Component
annotation. Then you can injector.get(type)
, where type
will be resolved from your @Input
. As per documentation, Service
is not actually injected until you ask for it (.get()
).