1

Angular : BehaviorSubject

 2 years ago
source link: https://dev.to/dipteekhd/angular-behaviorsubject-p1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Angular : BehaviorSubject

As we know multiple components share the common data and always need updated shared data. In such scenarios most of the time BehaviorSubject is used which acts as a single store to hold updated shared data.

  • BehaviorSubject is both observer and type of observable.
  • BehaviorSubject always need an initial/default value.
  • Every observer on subscribe gets current value.
  • Current value is either latest value emitted by source observable using next() method or initial/default value.

Let’s implement BehaviorSubject to understand a concept better!

For e.g In order tracking app, display total items in cart and total items in wish list on UI in header and dashboard section based on user action.

Now we have three components -
HeaderComponent, DashBoardComponent, TableComponent

Run Live

When user add items in the cart/wishList, total count needs to be updated in the header and dashboard component.

1.First create a BehaviorSubject in order service which holds the initial state of order count ,so that it can be used by any component.

2.Now all observers(3 components) need to subscribe to source observable to get current value and show it on UI.

3.When a user performs any action, call the next() method of source observable. When the next() method gets called it will update current count with new count and notifies updated count to all observers(3 Components) who subscribed to source observable.

This way BehaviorSubject makes components communication more effective.

Thanks for reading! If you found this helpful please share!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK