angular - 循环可观察数组并为每个元素与其他可观察数组合并

标签 angular rxjs

我有两个单独的函数返回不同的可观察值。

getCities(): Observable<City[]>

例如[{city: 'Amsterdam'}, {city: 'Rotterdam'}]

getLocations(city: string): Observable<CityLocation[]>

例如getLocations('Amsterdam')将返回 [{location: 'Westpoort'}, {location: 'Amsterdam-Noord' }]

我想将这两者结合起来,并有一个函数来返回一个像这样的可观察对象:

[ {city: 'Amsterdam', locations:[{location: 'Westpoort'}, {location: 'Amsterdam-Noord'}]}, {city: 'Rotterdam', locations: [{...}, {...}]} ]

所以基本上该函数应该遍历城市,然后对于每个城市,它应该获取位置并将所有内容合并到一个可观察对象中。

这是我现在拥有的:

getCombined() { return this.getCities().pipe( mergeMap(cities => { return from(cities).pipe( mergeMap( city => this.getLocations(city.city), (original, detail) => ({ ...original, locations: detail }) ), toArray(), map(locations => ({ ...cities, locations })) ); }) ); }

但不幸的是它不起作用并且控制台中没有错误。我不确定我做错了什么。

编辑:

Stackblitz 编辑:https://stackblitz.com/edit/angular-32wman

最佳答案

您可以对请求使用 forkJoin 并根据我的理解将位置添加为每个城市的数组。您修改后的代码:

getCombined() {
  return this.getCities().pipe(
    mergeMap(cities => forkJoin(
      cities.map(c => this.getLocations(c.city).pipe(
        map(locations => {
          c.locations = locations;
          return c;
        })
      ))
    ))
  );
}

STACKBLITZ

关于angular - 循环可观察数组并为每个元素与其他可观察数组合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875988/

相关文章:

javascript - Redux-Observable:修改状态触发后续 Action

rxjs - 链接 RxJS map 运算符和 ngrx 效果问题

javascript - 无法理解 zone.js 示例

angular - 如何以 Angular 制作多重代理

Angular Material - 防止 mat-stepper 在步骤之间导航

Angular Material Button 和 RxJS fromEvent 函数 - 没有 nativeElement 属性,只有 _nativeElement 属性

angular - 将 gRPC 与 Electron 14 结合使用

javascript - 如何处理 Angular 7 中的连接丢失页面?

javascript - 从订阅 Observable 获取返回值

redux - 从 redux-observable 中调度多个 Action