我有一个效果应该调用两个不同的 API(API1 和 API2)。
效果如下
$LoadKpiMission = createEffect(() =>
this.actions$.pipe(
ofType<any>(EKpiActions.GetMissionsByStation),
mergeMap(action =>
this.apiCallsService.getKpi(action.payload, '2016-04-18').pipe(
map(trips => ({ type: EKpiActions.GetMissionsSuccess, payload: trips })),
catchError(() => EMPTY)
)
)
)
);
这是服务的结构
getKpi(station: number, date: string) {
let Kpi = `http://192.168.208.25:8998/api/scheduling/circulation_by_date_and_station?orig=${station}&date=${date}`;
return this.http.get<ISchedules>(API1).pipe(
map(data => {
return this.formatDataToKpi1(data);
})
);
}
但是,我必须从 API2
检索其他数据,并将其与从 API1
返回的数据合并。
我应该在 formatDataToKpi1
函数内执行此操作。
我想知道如何并行运行请求并将返回的响应传递给formatDataToKpi1
并进行处理然后返回效果?
最佳答案
您可以使用forkJoin
RxJS 运算符。
如 documentation 上所述,
When all observables complete, emit the last emitted value from each.
这样,当两个请求的observables都完成后,就会返回,可以进行后续操作。
$LoadKpiMission = createEffect(() =>
this.actions$.pipe(
ofType<any>(EKpiActions.GetMissionsByStation),
mergeMap(action =>
const getKpi = this.apiCallsService.getKpi(action.payload, '2016-04-18');
const getKpi2 = this.apiCallsService.getKpi2();
forkJoin(getKpi, getKpi2).subscribe(([res1, res2] => {
// do the rest here
});
)
)
);
编辑:看起来我最初误解了你的问题 - 对变量名称有点困惑
getKpi(station: number, date: string) {
let Kpi = `http://192.168.208.25:8998/api/scheduling/circulation_by_date_and_station?orig=${station}&date=${date}`;
const api1 = this.http.get<ISchedules>(API1);
const api2 = this.http.get<ISchedules>(API2);
return forkJoin(api1, api2).pipe(
map(data => {
return this.formatDataToKpi1(data);
})
);
}
关于javascript - ngrx效果并行http调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59668456/