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

前端 未结 2 2020
青春惊慌失措
青春惊慌失措 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)
      }
    
    0 讨论(0)
  • 2020-12-28 16:35

    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"
    
    0 讨论(0)
提交回复
热议问题