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

不想你离开。 提交于 2019-11-29 09:28:23

问题


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(){
 this._jokeService.getData().subscribe();
}

Which in turn invokes this ( from a service) :

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

The problem is that on every click - I still see a new http request initiated :

Question:

Why doesn't shareReplay keeps the last value of the response?
How can I make my code to invoke the http only once and keep that value for future subscriptions ?

Edit: solution is here


回答1:


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



回答2:


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"


来源:https://stackoverflow.com/questions/51044291/using-sharereplay1-in-angular-still-invokes-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!