Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use Subject or BehaviorSubject in services when angular can detect latest values?

For example we have a service that has a list of items in it. When we change this list in the service, all of the components that are using this list will detect this change. for example if you add a new item all of the components will detect it. so why should we use subjects or BehaviorSubject when angular can detect changes itself ?

like image 861
Ali Rezaali Avatar asked Oct 20 '25 13:10

Ali Rezaali


1 Answers

Change detection is a great way to update the DOM after data changes. But what if you want to do more than that? What if a component needs to react to a change by executing some code?

If the change flows downwards in the component tree, you can do this by leveraging @Input. But what if you need to communicate sideways, upwards, or independent of the shape of the tree? Being constrained to unidirectional data flow, angular change detection can't help with that, so you need a different way to propagate changes for that. And that's what Observables are for.

like image 64
meriton Avatar answered Oct 22 '25 02:10

meriton