Reactive Patterns and Other Ways to Share Data
Learn about reactive patterns and some other ways to share data.
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
BehaviorSubject
calledselectedRecipeSubject
to 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 theselectedRecipeSubject
value asprivate
to protect it from external use; otherwise, any external process could call the next method and change the ...