在 Angular 中使用 shareReplay(1) - 仍然调用 http 请求?
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调用一次,缓存数据,推荐如下
您首先获取数据的可观察值:
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"
我创建了一个演示 (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调用一次,缓存数据,推荐如下
您首先获取数据的可观察值:
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"