模块A
declarations: [myComponent]
providers: [myServiceA]
模块B
declarations: [myComponent]
providers: [myServiceB]
myComponent由模块A和B共享
class myComponent {
constructor(?) {}
}
myServiceA和myServiceB共享相同的API。我的想法是myServiceA在本地存储数据(比如localstorage) myServiceB将数据存储在远程服务器上(比如说Firebase)。
如何根据加载组件的模块注入正确的myService?
答案 0 :(得分:2)
我想出了如何做到这一点:
为myServiceA和myServiceB创建抽象类,公开两个服务使用的相同API。
class abstract ParentService{
someFunc: (arg: string) => any;
}
class myServiceA implements ParentService{
// myServiceA implementation for someFunc
}
class myServiceB implement ParentService{
// myServiceB implementation for someFunc
}
在组件中注入父类。
class myComponent {
constructor(service: ParentService) {}
}
在模块A和B中添加不同的提供程序
模块A
declarations: [myComponent]
providers: [ { provide: ParentService, useClass: myServiceA } ]
模块B
declarations: [myComponent]
providers: [ { provide: ParentService, useClass: myServiceB } ]