我们尝试使用BehaviorSubject在多个组件之间共享API数据。在我的组件上,我触发了一个HTTP请求,并在返回响应后更新主题。
component.ts
onClick() {
this.service.getCompanies();
this.service.companiesList$.subscribe(companies => {
console.log(companies.length); // 0 and then 1
});
}service.ts
companiesList$ = new BehaviorSubject([]);
getCompanies() {
return this.http.get(myUrl).subscribe((res: any) => {
this.companiesList$.next(res.data);
});
}在请求完成后,如何才能仅访问BehaviourSubject发出的最后一个值?
发布于 2021-01-14 19:24:05
也许您可以尝试以下操作,将http请求的观察值保存在服务中,并对其应用shareReplay(1)运算符。然后,您可以在您的组件中使用它,如下所示:
component.ts
onClick() {
this.service.getCompanies().subscribe(companies => {
console.log(companies);
});
}service.ts
$companies = this.http.get(myUrl).pipe(shareReplay(1));
getCompanies() {
this.companies$;
}发布于 2021-01-14 19:02:57
虽然从技术上讲,您可以使用companiesList$.getValue(),但我建议您不要使用subscribe()在您的组件中创建订阅,而是使用AsyncPipe (ref)。它可能看起来像这样:
component.ts
companies$ = this.service.companiesList$.asObservable();
onClick() {
this.service.getCompanies();
}component.html
<div *ngIf="companies$ | async as companies">
<!-- your stuff -->
{{ companies.length }}
</div>发布于 2021-01-14 20:58:45
https://stackoverflow.com/questions/65717667
复制相似问题