2016-09-21 62 views
1

我想讓兩個Components在另一個Component對DOM事件作出反應時通過Service得到通知。訂閱多個Angular2組件到一個服務

這應該使用RxJS Subject Observable或其直接子類(BehaviorSubject或ReplaySubject)來實現。

這是模型:

  • TriggerComponent
  • NotificationService
  • FirstListeningComponent
  • SecondListeningComponent

無論這三個組件是父子。

我試圖按照這些方法:

  1. Angular2 Parent and Children communication via service
  2. RxJSObservable demo explanation

,但我沒能適應他們對我的需要。


請在正確的道路上檢查my live example on plnkr.co

我是誰?

謝謝

回答

3

我固定的plunker與working版本。

問題是爲每個組件創建了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' 
    } 
} 
+0

非常感謝! – Marian07