【问题标题】:RxJS Observable MergingRxJS 可观察合并
【发布时间】:2019-10-18 05:54:58
【问题描述】:

假设我有一个带有两个可能的 GET 请求的 REST 服务器。
一个是这样的:/allItems,另一个是:/{itemId}/picture
第一个将我服务器上的所有存储项作为数组返回(仅一次),其中每个项都有一个 Id。
对于他们每个人,我想请求他们各自的图片并将其与他们匹配。
像这样的:

this.http.get('/allItems').map(itemArray => {
   itemArray.forEach(item => {
       this.http.get('/' + item.id + '/picture')
                .subscribe(pic => item.pic = pic)
   return itemArray
 }
})

最后,我想返回 一个 Observable,它发出项目数组并映射了各自的图片,以便其他函数可以访问完整的数据。

可能值得一提:我正在使用 Angular/Typescript。

【问题讨论】:

标签: angular rxjs


【解决方案1】:

解决这个问题的一种方法可能是这样的:-

this.http.get('/allItems').pipe(
  mergeMap((itemsArray) => of(itemsArray)),
  mergeMap(item => this.http.get('/' + item.id + '/picture')
    .pipe(
      map(picture => { const a = { 'item': item, 'image': picture }; return a; })
    ),
    toArray()),
).subscribe();  ---> this will give the array of json with item and picture field.

【讨论】:

    【解决方案2】:

    @emkay 我重构了你的代码。我认为它看起来更好。 @mortom123 想要替换关键图片的对象值。

    this.http.get('/allItems')
     .pipe(
      .mergeMap((itemArray) => from(itemArray))
      .mergeMap((item) => this.http.get(`/${item.id}/picture`))
       .pipe(
        map((picture) => (
          {
            ...item,
            pic: picture
          })
     ).subscribe((data) => console.log(data));
    

    【讨论】:

      【解决方案3】:

      我从 cmets 了解到 OP 已经找到了解决方案。对于那些想知道的人,这就是您如何使用forkJoin,它等待数组。在返回可观察值之前完成 forEach() 循环。

      这是如何实现的:

      import { forkJoin } from 'rxjs';
      import { mergeMap } from 'rxjs/operators';
      
      this.http.get('/allItems').pipe(
        mergeMap(itemArray => {
          const observableList = [];
          itemArray.forEach(item => {
            observableList.push(this.http.get(`/${item.id}/picture`));
          });
          return forkJoin(observableList);
        )}
      ).subscribe(res => {
        console.log(res);
        // handle the rest here
      })
      

      【讨论】:

        猜你喜欢
        • 2016-06-18
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 2016-05-17
        相关资源
        最近更新 更多