首页 文章

将多个Angular2组件订阅到服务

提问于
浏览
1

当另一个 Component 对DOM事件做出反应时,我试图让两个 Components 通过 Service 得到通知 .

这应该使用RxJS Subject Observable或其直接子类(可能是BehaviorSubject或ReplaySubject)来实现 .

这是模型:

  • TriggerComponent

  • NotificationService

  • FirstListeningComponent

  • SecondListeningComponent

这三个组成部分都不是亲子 .

我试着遵循这些方法:

但我没有设法根据我的需要调整它们 .

请检查my live example on plnkr.co

我在正确的道路上吗?

谢谢

1 回答

  • 3

    我用一个working版本修复了你的plunker .

    问题是为每个组件创建了NotificationService的新实例 . 它应该只存在于主组件中创建的一个实例,并且组件应该共享该实例以进行通信 .

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello {{name}}</h2>
          <br>
          <trigger-component></trigger-component>
    
          <first-listening-component></first-listening-component>
          <second-listening-component></second-listening-component>
        </div>
      `,
      providers : [NotificationService]
    })
    export class App {
      constructor() {
        this.name = 'Angular2'
      }
    }
    

相关问题