【问题标题】:RXJS sequential HTTP requestRXJS 顺序 HTTP 请求
【发布时间】:2019-12-08 09:16:18
【问题描述】:

我想进行连续的 HTTP 调用并将响应合并到一个唯一的 observable 中。

问题是:我这样做的方式似乎是错误的。确实,我想将第二个请求中的数据合并到第一个请求中,但是我这样做的方式似乎是用第二个请求的结果替换了第一个请求的结果。

这是第一个调用的请求:

[{vehicule_id:123, statistics:{speed:60,rotation:38}},...]

第二个:

[{vehicule_id:123, name:"name",description:"description},...]

而我想要得到的结果:

[{vehicule_id:123, statistics:{speed:60,rotation:38}, name:"name",description:"description},...]

要知道的重要一点:第二个请求需要在第一个请求的响应中提供vehicule_id。 使用我的代码,第二个调用的响应会替换第一个调用的结果,而不是合并它们。

这是我的代码:

getUserVehiculesInfo(user_id: number, language: string): void {
this._data.getUserVehiculesInfo(user_id, language)
  .pipe(
    map(res => res.data[user_id]),
    switchMap(vehicules => forkJoin(vehicules.map(vehicule => this._data.getVehiculesInfo(tank.vehicule_id, language)))),
    tap(console.log)
  )
  .subscribe();
}

【问题讨论】:

    标签: rxjs observable rxjs-observables


    【解决方案1】:

    一旦你有了vehiculesInfo(forkJoin 的结果,你只需要将它们与车辆结合起来:

    switchMap(
      vehicules => forkJoin(...).pipe(
        map(infos => combineVehiculesAndInfos(vehicules, infos))
      )
    )
    

    【讨论】:

    • 有通用的方法吗?像一个 rxjs 方法?还是我必须创建我的?
    • 你必须自己创造。这与 RxJS 无关:您有两个数组都包含部分车辆信息,您需要将它们组合起来。这是业务逻辑。
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多