2016-05-13 65 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{