How to reuse angular observable across multiple components? (To avoid having to duplicate a request twice?)

Viewed 3809

I have a service "MyHttpService" that includes an observable like this:

grabData() {
return this.http.get('myaddress')
                         .map((res:Response) => {return res.json()})
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
}

I have 2 components. OneComponent and TwoComponent that both have "MyHttpService" injected that depend on the data returned by MyHttpService.

OneComponent loads up first. TwoComponent loads up after button click.

Within the onNgInit() of each component I have:

     this.myHttpService.grabData()
        .subscribe(
              data => {
 // do something to the data
});

Is it correct to assume that even though I have this subscribe in both components, that there are not going to be multiple HTTP requests called and that the call to "grabData()" when TwoComponent loads is the same data already pulled by OneComponent? Or will it make a new call? I want to avoid multiple HTTP requests to the same endpoint. If multiple calls are being made each time a component that has this is called, what is the best way to handle this so that I don't have multiple calls to the service each time I initialize TwoComponent?

3 Answers
Related