【问题标题】:Angular RxJs - fill array in the second stream (nested stream)Angular RxJs - 在第二个流(嵌套流)中填充数组
【发布时间】:2019-04-07 08:50:46
【问题描述】:

我的 Angular 应用程序中有一个特定模型的列表。此列表中的每个项目都有一个属性xyzList。这个xyzList 属性应该从取决于第一个请求的ID 的请求中填充。举个例子:

型号:

{
  id: number;
  name: string;
  xyzList: any[]
}

现在我有两个请求:

请求 1:填充模型,但不填充 xyzList

this.myVar$ = this.myService.getElements<Model[]>();

请求2:应填写xyzList

this.myService.getXyzElements<XyzModel[]>(idOfTheModelOfTheFirstRequest);

一开始我是这么想的:

this.myService.getElements<Model[]>()
.pipe(
  mergeMap(items => items)
  mergeMap(item => {
    return this.myService.getXyzElements<XyzModel[]>(item.id)
           .pipe(
             map(xyzList => {
               item.xyzList = xyzList

               return item;
             })
           )
  })
)

这不起作用,因为我已将列表展平并且我需要Observable&lt;Array[]&gt;,但我认为或多或少清楚我想要实现的目标。我假设我可以使用 forkJoin 来实现这一点,但我不知道如何。或者有没有办法将扁平列表转换回列表?

【问题讨论】:

  • 尝试添加toArray()作为管道的最后一个操作符

标签: javascript angular typescript rxjs rxjs6


【解决方案1】:

需要用到toArray(),因为mergeMap/flatMap是用来扁平化数据流数组的。它将返回一个数组而不是数据流。

this.myService.getElements<Model[]>()
.pipe(
  mergeMap(items => items)
  mergeMap(item => {
    return this.myService.getXyzElements<XyzModel[]>(item.id)
           .pipe(
             map(xyzList => {
               item.xyzList = xyzList

               return item;
             })
           )
  }),
  toArray()
)

【讨论】:

    【解决方案2】:

    嗯,我知道您有一个返回“项目”列表的服务函数。 EachItem 您需要调用另一个返回数据“xyzList”的服务函数。

    因此,每个“项目”必须是一个调用,然后,您创建一个“调用”数组

        myService.getElements().pipe(
            switchMap(result=>{
              //We can not return the "list"
              let calls:Observable[]=[]
                //Before, the first calls was the own result
                calls.push(of(result));
                //Each result push the calls
                result.forEach(e=>{
                    calls.push(myService.getXyzElements(e.id));
                })
    
                return forkJoin(calls).pipe(map(result=>{
                   //in result[0] we have the list of items
                   //In result[1] we have the Xyz of items[0]
                   //In result[2] we have the Xyz of items[1]
                   int i:number=0;
                   result[0].map(x=>{
                      i++;
                      return {
                          ...x,
                          xyzList:result[i]
                      }
                   })
                   return result[0];
                }))
            })
        ).subscribe(res=>console.log(res));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2016-10-12
      • 2015-11-24
      相关资源
      最近更新 更多