Subject vs BehaviorSubject in Angular

Published

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.

Source: Angular Questions

Published
Categorized as angular, behaviorsubject, subject-observer Tagged , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq