[英]Using shareReplay(1) in Angular - still invokes http request?
我創建了一個演示( ng-run ),其中有一個調用 Http 請求的按鈕。
單擊按鈕時,我調用此方法:
public getData(){
this._jokeService.getData().subscribe();
}
反過來調用這個(從服務):
public getData() {
return this.http.get(API_ENDPOINT).pipe(shareReplay(1))
}
問題是在每次點擊時 - 我仍然看到一個新的 http 請求被啟動:
題:
為什么 shareReplay 不保留響應的最后一個值?
如何讓我的代碼只調用一次 http 並保留該值以供將來訂閱?
編輯: 解決方案在這里
如果你每次都調用this.http.get(API_ENDPOINT).pipe(shareReplay(1))
,每次 http 請求都會被觸發。 如果要進行一次http調用並緩存數據,建議使用以下方法。
您首先獲得數據的 observable:
ngOninit(){
this.data$ = this._jokeService.getData().pipe(shareReplay(1));
}
現在訂閱多次:
public getData(){
this.data$.subscribe();
}
您的服務:
public getData() {
return this.http.get(API_ENDPOINT)
}
在役:
getData$ = this.http.get(API_ENDPOINT).pipe(shareReplay(1));
在組件中,需要取消訂閱,您可以通過單個 API 調用多次訂閱:
ngOninit(){
this.data$ = this._jokeService.getData$;
this.data$.subscribe()
}
在模板中,使用:
*ngIf="data$ | async as data"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.