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

前端 未结 2 2034
青春惊慌失措
青春惊慌失措 2020-12-28 15:54

I\'ve created a demo (ng-run) where I have a button which invokes an Http request.

When the button is clicked, I invoke this method :

public getData         


        
2条回答
  •  粉色の甜心
    2020-12-28 16:23

    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)
      }
    

提交回复
热议问题