【问题标题】:Angular Map and mergeMap rxjs6 operatorsAngular Map 和 mergeMap rxjs 运算符
【发布时间】:2019-01-14 12:10:40
【问题描述】:

新手问题:

我正在尝试将我的数据从 rest API 导出到 firebase。

我正在使用 Angular6RxJS 6

getByTag(tag:string) {
  return this.http.get(this.URL + '/get/listings/', { headers })
    .pipe(
      map((res: Listings) => res.items),
      // How do I add an additional property to each of these items? eg res.items.inserted = new Date();
      // How do chain each of these res.items to another function called exportToFirebase(res.item))
    );
}

我的数据如下所示: https://pasteboard.co/HWp1hUb.jpg

我尝试了 map 函数,但我从 API 传入的数据流是一个数组数组,所以 我尝试了mergeMap但没有成功 (https://www.learnrxjs.io/operators/transformation/mergemap.html)

我尝试使用do() 语句来触发exportToFirebase(res.item),但看起来我完全偏离了轨道:-P

预期结果:创建一个循环以将列表类型的项目参数发送到我的服务函数exportToFirebase(res.item)

有问题吗?

  1. 如何为这些项目中的每一项添加附加属性?例如res.items.inserted = new Date(); ?

  2. 如何将这些res.items 链接到另一个名为exportToFirebase(res.item)) 的函数?

【问题讨论】:

  • 那么你的问题是exportToFirebase(res.item)返回一个Observable?

标签: angular angular6 rxjs6


【解决方案1】:

mergeMap 在您的情况下是无用的,因为它是为展平可观察对象而创建的。

所以map 操作员应该完成所有工作。

getByTag(tag:string) {
  return this.http.get(this.URL + '/get/listings/', { headers })
    .pipe(
      map((res: Listings) => res.items),
      map((list: any[]) => {
        return list.map(sublist => sublist.map(item => {...item, inserted: new Date()}));
      })
    );
}

更新

您可以使用reduce 来展平您的阵列:

map((res: Listings) => res.items.reduce(((arr, list) => arr.concat(list), [])),

map((list: any[]) => {
  return list.map(item => {...item, inserted: new Date()});
})

要链接你可以使用do/tap:

tap((list: any[]) => {
  list.forEach(item => {
    exportToFirebase(item)
  });
})

所以exportToFirebase 的实际执行在你身边,如果它返回 Observable 或 smth,我想知道该函数的签名是什么

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,并且您想为结果数组中的每个项目添加一个字段,然后将每个项目单独传递给 exportToFirebase() 函数,那么可能会用到这样的东西:

    getByTag(tag:string) {
      return this.http.get(this.URL + '/get/listings/', { headers })
        .pipe(
          map((res: Listings) => res.items)
        )
        .subscribe(items => {
          items.forEach(i => {
            i.inserted = new Date();
    
            exportToFirebase(i);
          });
        });
    }
    

    如果您不想使用订阅,也可以使用tap 运算符,正如另一个答案所述。

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 2018-07-31
      • 1970-01-01
      • 2019-01-25
      • 2019-12-29
      • 2019-04-28
      • 1970-01-01
      • 2019-07-09
      • 2018-03-09
      相关资源
      最近更新 更多