我有两个独立的组件,它们在给定的时间在同一视图中是可见的。在他们的ngOnInit()-method中,我从服务订阅了相同的观察值。这会导致两个不必要的网络调用。如何将来自服务的响应共享给两个订阅者,以便只发生一次网络调用?
我的服务调用代码是:
getDashboardViewModel (): Observable<DashboardViewModel> {
return this.get<DashboardViewModel>(Constants.DashboardApiUrl);我在两个组件上订阅它的方式是:
ngOnInit() {
this.dashboardService.getDashboardViewModel().subscribe(dashboardVM => this.dashboardViewModel = dashboardVM);
}如何才能使网络调用只发生一次,且两个组件都获得数据。我使用的是Angular 7。
发布于 2020-03-04 21:45:30
你可以这样做:
@Injectable()
export class Service{
dashboardModel: ReplaySubject<Model> = new ReplaySubject<Model>'
constructor(private _http: HttpClient) {
this._http.get<Model>(url).subscribe((model: Model) => {
this._dashboardModel.next(model);
});
}
}然后,在组件中的init调用中,只需执行以下操作:
this._service.dashboardModel.first().subscribe((model) => {});ReplaySubject允许检索由可观察对象发出的最后n个值。
https://stackoverflow.com/questions/60527347
复制相似问题