Reputation: 3482
Well here is a plnk, http://plnkr.co/edit/y7PZONWELeG4f2Ywbw4k.
@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
}}
I am trying to to pass a message from child to parent via service with observable, but it doesn't work. Here is example at https://angular.io/docs/ts/latest/cookbook/component-communication.html (Parent and children communicate via a service). I have 2 solutions - first give no clue at all, nothing passed to console, second - gives subscription completed but i didn't send any complete() messages. So what the problem with this ?
Upvotes: 1
Views: 66
Reputation: 657376
If you want to share a service between components, then only provide it on a common ancestor but not on every component where you want to inject it.
At every place where you add it to providers: [MsgService]
a new different instance is created, but you need a shared one.
@Component({
selector: 'messages',
template: `<div>Message from {{id}} chat</div>`
//providers: [MsgService]
})
export class Chat{
Upvotes: 3