Exploring the reactive pattern to share data
Angular services are powerful and efficient for creating common references for sharing both data and business logic between components. We will 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, let's explain the steps to implement a reactive pattern to share data between unrelated or sibling components.
Step one – creating a shared service
We will 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 is a strongly typedBehaviorSubject...