Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe to same service call without calling service multiple times in Angular 7

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.

like image 755
Waleed Naveed Avatar asked Nov 26 '25 21:11

Waleed Naveed


1 Answers

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.

like image 113
David Gonzalez Avatar answered Nov 28 '25 17:11

David Gonzalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!