Using shareReplay(1) in Angular - still invokes http request? Using shareReplay(1) in Angular - still invokes http request? angular angular

Using shareReplay(1) in Angular - still invokes http request?


If you call every time this.http.get(API_ENDPOINT).pipe(shareReplay(1)), each time http request will be triggered. If you want to make http call once and cache data, the following is recommended.

You first get the observable for data:

 ngOninit(){    this.data$ =  this._jokeService.getData().pipe(shareReplay(1));    }

Now subscribe multiple times:

 public getData(){     this.data$.subscribe();    }

Your service:

public getData() {    return this.http.get(API_ENDPOINT)  }


In service:

getData$ = this.http.get(API_ENDPOINT).pipe(shareReplay(1));

In component, need to unsubscribe and you can subscribe multiple times with single API call:

ngOninit(){   this.data$ =  this._jokeService.getData$;   this.data$.subscribe() }

In template, use:

*ngIf="data$ | async as data"