I have a parent container component and a lot of child components inside this parent container. Every child component is a tile, which renders piece of information. Each tile has subscription on a store and it observes for a boolean value. So is it a good practise, that there are so many subscriptions? Or is it better to have one subscription in the parent component which will pass information via @Input to each component?
CodePudding user response:
It is better for cleaner code to have one subscription in parent and pass information from parent component.
CodePudding user response:
We use Input and Output Decorators to Pass information from one Component to Another like Parent and Child.@Input/@Output API will not help you everywhere. You have to manage in parent and child, if you want two way communication. Later, over the time it becomes complex to manage. Other downsides are that you can't do sibling to sibling data sharing. What if (for some unforeseen reason) you'd like tiles to share data? So I would prefer subscriptions.
My rule of thumb is, that if is anything but 1-2 simple data pieces I will setup subscription using | async pipe. And if I forsee using data in template more than 1-2 places I will use regular subscribe() - otherwise you will end up with too many places in template where you need to unpack the data. Then finally I decide if subscription should be something special. Like an BehaviourSubject which always emits something or ReplaySubject, which emits when it has something. I like to move subscriptions to their related services. Keeping so called business logic (data manipulation) at the service level. Then I know myself that all logic is in service, and everything related to what user sees is at component level - like it should be. Also helps when some backend guys come checking the code for some reason it would make more sense to them.
If you find yourself having too many subscriptions, which can happen also quite fast you could concat your data to a more complex object. You keep your data object up-to-data and on data change, emit this data object to all subscribers which read out only information that concerns them.
Other obvious end result is cleaner code. Few lines of subscription data vs many lines of @Inputs/@Ouputs in typescript code, in html in one or many components. When using subscriptions you can also then take full advantage god-ness that rxjs offers.
tl;dr prefer subscriptions over Input/Output.
