DEV Community

Discussion on: Looking for Angular Architecture Advise

Collapse
 
ayhanyildiz profile image
Ayhan Yildiz • Edited

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?

-When you fetch data from http it is not stream and it will be completed. If you want to share same fetched data with new subscribers you can use any Subject helpers to create new observable and share the data. These all needs to be done in service layer since they are built for the purpose of sharing data and creating instances. Please read angular dependency injection to grasp better.

Should I instantiate Observables/Subjects when declaring their variables? Or should I instantiate in the constructor?

  • You can initialize Subjects as Class property. Constructor mostly used for injection in angular.

When it comes to subscribe/unsubscribe I should probably use the ngOnInit() and ngOnDestroy() hooks, which are available in Components only... so I guess I should never subscribe/unsubscribe in my services, right?

  • If you subscribe in Service it is bit difficult to unsubscribe. Leave subscribing/unsubscribing to Components.

Is it a bad pattern to have an Observable foo$ together with its resolved data foo in the same class?

  • It will be if you don't update your cached data. You can have cached data when app loads and shared that and never bother with subscription. There are cases you can use it. Observables are not only way to share data.