Javascript Ngrx效应并行http调用
我有一个效果,应该调用两个不同的API API1和API2 效果是这样的Javascript Ngrx效应并行http调用,javascript,angular,typescript,rxjs,ngrx,Javascript,Angular,Typescript,Rxjs,Ngrx,我有一个效果,应该调用两个不同的API API1和API2 效果是这样的 $LoadKpiMission = createEffect(() => this.actions$.pipe( ofType<any>(EKpiActions.GetMissionsByStation), mergeMap(action => this.apiCallsService.getKpi(action.payload, '2016-04-18').pipe
$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操作符
如合同上所述
当所有观测值完成时,从每个观测值发出最后发出的值
这样,当两个请求中的可观察项都已完成时,它将被返回,您可以执行后续操作
$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);
})
);
}
您可以使用forkJoin RxJS操作符
如合同上所述
当所有观测值完成时,从每个观测值发出最后发出的值
这样,当两个请求中的可观察项都已完成时,它将被返回,您可以执行后续操作
$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);
})
);
}
查看ForkJoin查看ForkJoin正如我提到的,我应该在“getKpi”函数中进行所有调用,并将API调用响应数据发送到formatdatatokpi1。。并且不使用不同的函数。。formatkpidata将转换两个http的结果calls@infodev啊,我现在明白了。我已经编辑了我的代码,正如我提到的,我应该在“getKpi”函数中进行所有调用,并将API调用响应数据发送到formatdatatokpi1。。并且不使用不同的函数。。formatkpidata将转换两个http的结果calls@infodev啊,我现在明白了。我已经编辑了我的代码