Angular 2 dynamic dependency injection based on @Input()

前端 未结 4 977
长发绾君心
长发绾君心 2020-12-25 13:18

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

4条回答
  •  时光说笑
    2020-12-25 13:52

    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()).

提交回复
热议问题