【问题标题】:Angular use multiple instances of service of parent component to childAngular对子组件使用多个父组件服务实例
【发布时间】:2020-11-19 23:17:48
【问题描述】:

我看过这个帖子:Using multiple instances of the same service。是否可以从父级到子级使用相同的多个服务实例?

例如,我在 ParentComponent 中有一个 ElementService,并且有 2 个该服务的实例

{ provide: 'instance1', useClass: ElementService},
{ provide: 'instance2', useClass: ElementService},

我应该如何在Child1Component 中使用instance1 和在Child2Component 中使用instance2

【问题讨论】:

    标签: angular service components angularjs-injector


    【解决方案1】:

    当您在组件的装饰器中指定提供程序时,注入的提供程序将特定于该组件,请参阅Angular - Providing dependencies

    这也是关于 dependency injection 的有用信息

    因此,只需在两个组件的 providers 数组中指定服务,您就应该在两个组件中拥有该服务的唯一实例。

    @Component({
        selector: 'app-page',
        templateUrl: './page.component.html',
        styleUrls: ['./page.component.scss'],
        providers: [
            ElementService
        ]
    })
    export class PageComponent implements OnInit {...
    

    【讨论】:

      【解决方案2】:

      您可以在每个子组件的构造函数中(也可以在父构造函数中)注入一个命名的提供者:

      Child1Component

      constructor(@Inject('instance1') private service: ElementService) { }
      

      Child2Component

      constructor(@Inject('instance2') private service: ElementService) { }
      

      这是一个带有计数器的工作示例:https://stackblitz.com/edit/angular-ivy-usorby?file=src%2Fapp%2Fchild1%2Fchild1.component.ts

      【讨论】:

      • 嗨 Gerome,谢谢,但我需要的是 2 个实例应该在 parent 中声明,因为 parent 也会订阅服务的 2 个实例。在您的示例中,AppComponent 还将侦听 child1 和 child2 的 DataService 实例的变化。
      • 也在父组件中注入提供者。我更新了 stackblitz 示例。
      • 嗨,你能回答这个问题吗? stackoverflow.com/questions/64274610/…
      • 你好,问题中已经包含的答案(将服务作为提供者直接添加到组件元数据中)应该可以工作。
      猜你喜欢
      • 2021-01-24
      • 2017-04-06
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2017-07-23
      • 2017-06-10
      • 2020-08-08
      • 2017-12-07
      相关资源
      最近更新 更多