Sharing Data between Components in Angular | Subject and BehaviorSubject

Описание к видео Sharing Data between Components in Angular | Subject and BehaviorSubject

#Subject and #BehaviorSubject


Share data between any components

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should you a shared service. When you have data that should always been in sync, I find the RxJS `BehaviorSubject` very useful in this situation. The main benefit that a BehaviorSubject ensures that every component consuming the service receives the most recent data.


In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a current Message variable handle this data stream as an observable that will be used by the components. Lastly, we create function that calls next on the BehaviorSubject to change its value.

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Now if we create a function in any one of these components that changes the value of the message. when this function is executed the new data it's automatically broadcast to all other components.

Комментарии

Информация по комментариям в разработке