Angular BehaviorSubject Service

Angular BehaviorSubject Service

Image for post

State management in Angular does not have one single prescribed pattern. A data store (similar to ngrx?s store) is a centralized single source (singleton) of state. This fits well with maintaining selected items on the frontend that an app needs to know about. If multiple components care about what a user has selected or input, that can be nicely held in a store.

RxJS has observers (consuming interface) and observables (push interface). A Subject is both an observer and observable. A BehaviorSubject a Subject that can emit the current value (Subjects have no concept of current value). That is the confusing part. The easy part is using it.

The BehaviorSubject holds the value that needs to be shared with other components. These components subscribe to data which is simple returning the BehaviorSubject value without the functionality to change the value. Here is a more detailed breakdown of asObservable. In updateDataSelection we call next and pass in a new value to the BehaviorSubject.

This is a very simple but powerful pattern. What about remote data? That can work too. More to come on that.

Next step in learning stores is to dive all in with ngrx.

If you found this helpful at all please hit the recommend button . It helps this post reach more people.

I post on twitter about new articles here. I would also really enjoy hearing any response. Just leave them below!

22