How To Share Data Between Angular Components Using Rxjs Behaviorsubject.
To share Data Between Angular Components using
RxJs BehaviorSubject, we would need to create a shared service.
That way the Angular Application components can subscribe to this shared service and get the give data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
The RxJs BehaviorSubject makes sure all components always receive the up to date data on subscription to dataSource. BehaviorSubject has a getValue() to get the values of data source.
Now that we have our data source set with initial data, lets see how we can get this data in our parent components and children components.
And also how we can change the data from both the parent components and children components.
The <strong>dataSource BehaviorSubject</strong>, holds the current value of data.
The currentData variable, handles our data as an observable that can be subscribe to by the components to get the current data. The <strong>changeData()</strong> method calls next on the <strong>dataSource BehaviorSubject</strong> to change the value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Child Component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
In both the parent and child components, to get the current data, we simply inject the shared service, then subscribe to the <strong>currentData</strong> observable to get the value. Also, in both components, to change the current value of our data, we simply just call the changeData(newData: any) function, with new data. That's it!
















