使用共享组件进行Angular 2依赖注入

时间:2016-11-16 11:55:19

标签: angular dependency-injection

模块A

declarations: [myComponent]
providers: [myServiceA]

模块B

declarations: [myComponent]
providers: [myServiceB]

myComponent由模块A和B共享

class myComponent {
  constructor(?) {}
}

myServiceA和myServiceB共享相同的API。我的想法是myServiceA在本地存储数据(比如localstorage) myServiceB将数据存储在远程服务器上(比如说Firebase)。

如何根据加载组件的模块注入正确的myService?

1 个答案:

答案 0 :(得分:2)

我想出了如何做到这一点:

  1. 为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
    }
    
  2. 在组件中注入父类。

     class myComponent {
        constructor(service: ParentService) {}
    }
    
  3. 在模块A和B中添加不同的提供程序

  4. 模块A

    declarations: [myComponent]
    providers: [ { provide: ParentService, useClass: myServiceA } ]
    

    模块B

    declarations: [myComponent]
    providers: [ { provide: ParentService, useClass: myServiceB } ]