I have two seperate components which at a given time is visible in the same view. In their ngOnInit()-method I subscribe for the same Observable from a service. This results in two network calls which is unnecessary. How can i share the response from the service to both subscribers so only one network call happens?
My service call code is:
getDashboardViewModel (): Observable<DashboardViewModel> {
return this.get<DashboardViewModel>(Constants.DashboardApiUrl);
And the way i have subscribed it on both components is:
ngOnInit() {
this.dashboardService.getDashboardViewModel().subscribe(dashboardVM => this.dashboardViewModel = dashboardVM);
}
How can i do so that network call occur only once and both the components get the data. I am using Angular 7.
You could do something like this:
@Injectable()
export class Service{
dashboardModel: ReplaySubject<Model> = new ReplaySubject<Model>'
constructor(private _http: HttpClient) {
this._http.get<Model>(url).subscribe((model: Model) => {
this._dashboardModel.next(model);
});
}
}
and then on your init call in your components simply do:
this._service.dashboardModel.first().subscribe((model) => {});
ReplaySubject allows to retrieve the n last value emitted by the observable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With