Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
We use BehaviourSubject
to share the data with multiple components using a shared service.
For example, if we want to notify other components of the data change. Then we have to do two simple tasks.
BehaviourSubject
& an Observable
of that BehaviourSubject
in a service.Observable
in other components.I have created the below service to notify another component to log out the user from the application.
Read the comments marked with 1, 2, 3 & 4 steps. They explain their usage itself.
In this, the logoutUser()
method of DataService
will update the value of BehaviourSubject
so that all & the observable (i.e. getLogoutStatus
) of this BehaviourSubject
will broadcast the message to all subscribers.
In this component, we have subscribed thegetLogoutStatus
observable. The subscription handle will be executed every time whenever there is a change in the value of BehaviourSubject
.