Reactive Patterns and Other Ways to Share Data
Explore how to implement reactive data sharing between unrelated Angular components using services combined with BehaviorSubject. Understand creating read-only observables for shared state, updating data through service methods, and subscribing to changes in components to synchronize application state efficiently.
The reactive pattern for sharing data
Angular services are powerful and efficient for creating common references for sharing both data and business logic between components. We’ll combine Angular services with observables, more specifically BehaviorSubject, to create stateful, reactive services that will allow us to synchronize the state efficiently across an entire application. So, in the following subsections, we’ll explain the steps to implement a reactive pattern to share data between unrelated or sibling components.
Creating a shared service
We’ll create an Angular service called SharedDataService using the Angular CLI, as usual, under the src/app/core/services folder.
ng g s SharedData
In the SharedDataService class, we need to create the following:
A private
BehaviorSubjectcalledselectedRecipeSubjectto multicast the value of the currently selected recipe, which represents the data to be shared. It’s a strongly typedBehaviorSubject. The type of emissions will beRecipe. We initialize it with an empty object as the default value, since initially, we don't have any selected value. We define theselectedRecipeSubjectvalue asprivateto protect it from external use; otherwise, any external process could call the next method and ...