From a technical point of view, both “solutions” are pretty much equal - since they basically do the same as your personal taste if you just want to consider your two solutions.
But in general: try to avoid manual subscriptions altogether.
There are a few things you can improve (the following code is based on the assumption that you would rather show an outdated list that is updating in the background than showing a download indicator):
- try to avoid manual subscriptions (especially (!!) in components) -> use
async -pipe instead - try to avoid stateful components (even if possible, if possible) → use threads instead
Your service
export class HospitalService { allHospitals$: BehaviorSubject<IHospital[]> = new BehaviorSubject<IHospital[]>([]);
Your component (=> just enter the service)
constructor(private hospitalService: HospitalService) {
Component template (=> the asynchronous channel automatically automatically controls the subscription and automatically unsubscribes, so you don’t have to worry about ect memory leak ...)
<div *ngFor="let hospital of (hospitalService.allHospitals$ | async)"> {{hospital.name}} </div>
A fourth (but much more advanced) solution would be to use a central repository such as ngrx . Thus, ngrx is basically part of allHospitals$ will be moved to a centrally-managed storage module, and you will strictly separate your application so that the service does nothing but collect and process data, it will do nothing in the storage, except for storing and emitting data, and the component will do nothing but display the data.
source share