我有两个独立的组件,它们在给定的时间在同一视图中是可见的。在他们的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个值。
发布于 2020-03-05 01:22:41
但是,如果数据请求可以通过解析器触发,事情就会更简单,您可以遵循前面的答案之一,即使用智能容器组件来包装需要使用数据的组件。该智能容器可以触发http请求,但是在服务上,通过点击设置管道来将响应值设置为BehaviorSubject,然后在需要数据的组件上使用异步管道来管理数据订阅。
以下是该服务的代码示例:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
}) export class ExampleService {
private _data: BehaviorSubject<any> = new BehaviorSubject({ properties: [], geometry: [] });
public data$: Observable<any> = this._data.asObservable();
constructor(private http: HttpClient){}
set data(data) {
this._data.next(data);
}
get data() {
return { ...this._data.value };
}
public getEarthquakeData(url): Observable<any[]> {
return this.http.get<any[]>(url)
.pipe(
tap(
(data: any) => this.data = data
)
)
}
}发布于 2020-03-04 21:41:24
NgRx是一个用于在Angular中构建反应式应用程序的框架。NgRx提供了状态管理、副作用隔离、实体集合管理、路由器绑定、代码生成和开发人员工具,这些工具在构建许多不同类型的应用程序时增强了开发人员的体验。
特别是,当您构建具有大量用户交互和多个数据源的应用程序时,当在服务中管理状态不再足够时,您可以使用NgRx。
可能回答“我需要NgRx”这个问题的一个很好的答案是SHARI原则:
共享状态( services.
https://stackoverflow.com/questions/60527347
复制相似问题