2016-05-13 119 views
1

那麼這裏是一個plnk,http://plnkr.co/edit/y7PZONWELeG4f2Ywbw4k消息傳遞與observable不起作用

@Injectable() 
export class MsgService{ 
// First solution sends nothing to the console in ChatList 
private msgSource = new Subject<string>() 

msgEvent$ = this.msgSource.asObservable() 

// Second solution -> sends 'completed' in the ChatList comp 
//chat_id; 
//msg = Observable.of(this.chat_id) 

sendMsg(id){ 
    this.msgSource.next(id) 
    //this.chat_id = id 
}} 

我想通過可觀察的服務將消息從子項傳遞給父項,但它不起作用。這裏的例子是https://angular.io/docs/ts/latest/cookbook/component-communication.html(父母和孩子通過服務進行交流)。我有2個解決方案 - 首先根本沒有線索,沒有傳遞給控制檯,第二個 - 給訂閱完成,但我沒有發送任何完整()消息。那麼這有什麼問題呢?

回答

3

如果你想在組件之間共享一個服務,那麼只在一個共同的祖先上提供它,而不是在你想要注入它的每個組件上提供它。

在每一個你添加到providers: [MsgService]的地方新建一個不同的實例已創建,但你需要一個共享的實例。

@Component({ 
    selector: 'messages', 
    template: `<div>Message from {{id}} chat</div>` 
    //providers: [MsgService] 
}) 

export class Chat{