0

I have a problem few of my components need same data from backend. So they all calls getDataMethod(); it looks like this

public getData(): Observable<any> {
  return this.http.get<any>(this.backendUrl);
}

response come in 5 seconds during this time I approximately call this method 3-4 times. So my question is were any they to return same observable to multiple subscribers?

F0XS
  • 1,275
  • 3
  • 14
  • 19
Aurimas1
  • 3
  • 1

2 Answers2

1

You could publish the response as a replaySubject like so

public getData(): Observable<any> {
  return this.http.get<any>(this.backendUrl)
                .publishReplay(1)
                .refCount();
}

this will replay the results from the server without making a call to your api endpoint each time someone subscribes to the observable.

JoshSommer
  • 2,450
  • 17
  • 21
-1

you can use a "cache" variable.

data:any
public getData(): Observable<any> {
  if (this.data)
     return Observable.of(this.data);
  else
     return this.http.get<any>(this.backendUrl).do((data:any)=>
       {
           this.data=data
       });
}
Eliseo
  • 39,135
  • 4
  • 22
  • 51