Angular:在组件上动态注入服务

时间:2017-06-13 09:39:24

标签: angular dependency-injection angular-services

我需要动态创建服务实例并将其分配给某些对象。所有这些都是在运行时根据用户操作发生的 这就是我想要实现的,或多或少:

testComponent.ts

@Input() serviceType: any;

// Injector is provide by the upper component
constructor(injector: Injector) {
        super();
        // testComponent knows nothing about fooService (only provided injector does)

        // Could be a string or an object
        this.serviceInstance = injector.get(this.serviceType);

        // It is now able to use a fooService method
        this.serviceInstance.getData().subscribe((data)=>{
            console.log(data);
        });
    }

fooService.ts     

// common method exposed by all services
public getData() { 
   // does something
}

这是正确的方法吗? 如果在任何地方都没有提供所需的服务并且必须动态导入该怎么办?

1 个答案:

答案 0 :(得分:0)

绝对可以做到这一点,您只需要在适当的NgModule中为该服务注册第二个提供程序即可

@NgModule( {
imports: [
],
providers: [
    AppUserApiService,
    { provide: 'AppUserApiService', useExisting: AppUserApiService },
]
}
相关问题