将多个Angular2组件订阅到服务

时间:2016-09-21 15:53:58

标签: angular rxjs observable

我正在尝试让两个Components在另一个Service对DOM事件作出反应时通过Component收到通知。

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

这是模型:

  • TriggerComponent
  • NotificationService
  • FirstListeningComponent
  • SecondListeningComponent

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

我试图遵循这些方法:

  1. Angular2 Parent and Children communication via service
  2. RxJSObservable demo explanation
  3. 但我无法根据自己的需要调整它们。


    请检查my live example on plnkr.co

    我是在正确的道路上吗?

    谢谢

1 个答案:

答案 0 :(得分: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'
  }
}
相关问题