I have a service ->
subject = new Subject<any>();
constructor (){
this.subject.next('hello');
}
getsubject():Observable<any>{
return this.subject.asObservable();
}
and component ->
name:string;
subscription : Subscription;
constructor(private serv:SService) {
this.subscription=this.serv.getsubject().subscribe(message=>{console.log('hello');});
}
as you can see, i'm passing hello message from service to subscribers, but in component subscriber is not getting that value, even it's not logging any word.
plunker example
The observable probably fires from the constructor before the component subscribes to it. So the component misses the message.
Instead of putting this.subject.next('hello') in the constructor, make a method.
sendMessage (){
this.subject.next('hello');
}
You can then call the this.serv.sendMessage() from the component, and it will already be subscribed.
Alternatively you can look into BehaviorSubject which will hold onto the most recent value, and give it right away when something subscribes to it.
Its working. plunker you need to add this code. So subject will emit value if nobody subscribed to it at that time nobody will know that it emitted value. and when somebody subscribe it will not emit last value(BehaviorSubject will) .
passToServ() {
this.subject.next(2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With