Angular subject subscription is not working

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 your subscriber is component file, one of the reason can be disremembering of adding selector of your component somewhere in your application. You must register component for example in app.component.html.

Tags:

Angular

Rxjs