将多个 Angular2 组件订阅到一个服务

Subscribe multiple Angular2 components to a Service

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

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

这是型号:

这三个组件都不是父子组件。

我尝试遵循这些方法:

  1. Angular2 Parent and Children communication via service

但我没能根据自己的需要调整它们。


请检查 my live example on plnkr.co

我走的路对吗?

谢谢

我用 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'
  }
}