After building one or two Angular applications it's time to ask if I'm doing things right. There might be a lot of beginner tutorials for Angular out there, but it's hard to find architectural best practices. My most urgent question is:
- How long to keep using data as an Observable? When can/should I "resolve" it to its actual data e.g. with the async pipe?
The answer might be "as long as possible", so I should always try to use an observable and only "resolve" it in the the html template where the data is finally being shown.
But I guess it's easier to use an observable as short as possible by resolving it in the parent component and providing the data as input for the child components like so:
I really don't know the answer. And here are some more questions I keep asking myself:
- Since I only want to fetch data from my http server once, but use it several times - where do I use ReplaySubjects? In the Services or in the Components?
- Should I instantiate Observables/Subjects when declaring their variables? Or should I instantiate in the constructor?
- When it comes to subscribe/unsubscribe I should probably use the
ngOnDestroy()hooks, which are available in Components only... so I guess I should never subscribe/unsubscribe in my services, right?
- Is it a bad pattern to have an Observable
foo$together with its resolved data
fooin the same class?
Please share your recommendations!
Attributions for the cover image go to jannoon028 from www.freepik.com.