[英]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.