Ngrx效果并行http调用 [英] Ngrx effect parallel http call

查看:69
本文介绍了Ngrx效果并行http调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的效果是应该调用两个不同的API(API1和API2).

I have an effect that should call two different APIs (API1 and 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 返回的数据合并.

However, I have to retrieve additional data from API2 and merge it with the data returned from API1.

我应该在 formatDataToKpi1 函数中执行此操作.

I should do that inside the formatDataToKpi1 function.

我想知道如何并行运行请求,并将返回的响应传递给 formatDataToKpi1 ,然后进行处理,然后返回效果?

I would like to know how to run requests in parallel and pass the returned responses to formatDataToKpi1 and do treatment then return to the effect ?

推荐答案

您可以使用 forkJoin RxJS运算符.

You can make use of the forkJoin RxJS operator.

文档

所有可观测值完成后,从每个可观测值中发出最后一个发出的值.

When all observables complete, emit the last emitted value from each.

这样,当两个请求的可观察值都完成时,它将被返回,并且您可以执行后续操作.

This way, when the observables from both requests have been completed, it will be returned, and you can carry out the subsequent operations.

$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
      });

    )
  )
);


看来我起初误解了您的问题-变量名有些困惑


Looks like I have initially misunderstood your question - Was a bit confused by the variable names

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);
    })
  );
}

这篇关于Ngrx效果并行http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆