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

问题描述 投票:0回答:1

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

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
}

这是正确的方法吗?如果没有在任何地方提供所需的服务而必须即时导入该怎么办?

angular dependency-injection angular-services
1个回答
0
投票

这完全可以做到,您只需要像这样在适当的NgModule中注册服务的第二个提供者,就可以了>>

@NgModule( {
imports: [
],
providers: [
    AppUserApiService,
    { provide: 'AppUserApiService', useExisting: AppUserApiService },
]
}
© www.soinside.com 2019 - 2024. All rights reserved.