I am passing data between 2 independent components using shared service. When I used a subject in my shared service, I could not see the subscribed data in html of the subscribed component but could see it in the console after subscribing. Whereas if I use Behaviorsubject, it worked fine. Can anyone explain me the reason for this.
sharedservice.ts:
//code with subject (not working)
private msgStatistics = new Subject<any>();
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
//code with BehaviorSubject (working)
private msgStatistics = new BehaviorSubject<Object>(null);
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
component2.ts:
this.shared_service.msgStatistics$.subscribe(res => {
this.message = res
console.log(this.message)
})
the above console is printing the value of message in both the cases but it is not rendering in html for subject.
The difference between
SubjectandBehaviorSubjectis thatBehaviorSubjectwill retain last value. Any new subscriber will receive that value.With
Subjectif values emitted are received only those subscribers that are already subscribed. If a new subscriber arrives it will belate from the partyand receive nothing.You can try a simple experiment:
Create a
BehaviorSubjectand initialize it with some well known value. Now that values is there until next one is emitted.Now create few subscriber to that. All of them will receive that well known value.
Do the same with Subject. You cannot initialize it so after creating it try to emit something.
Then create subscribers, nobody will receive anything.
UPDATE
I created a little demo to showcase the difference.
Once you open the Stackblitz page, you will see two columns [Subject, BehaviorSubject]
Open the console to be able to see the output. At this point no subscribers exists. You can change the value to be emitted. And then click on "Emit" Nothing will happen only a log statement that method is called.
Sample output:
Now the real test:
Create one subscriber for Subject and for BehaviorSubject.
Observe the console it should be something like this:
And here you can see the difference. Once a new subscriber arrives to
BehaviorSubjectit receives the last emitted value. WithSubjectthat is not the case. Previously emitted value will not be emitted for new subscriber.Stackblitz