Angular Map和mergeMap rxjs6运算符

时间:2019-01-14 12:10:41

标签: angular angular6 rxjs6

新手问题:

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

我正在将 Angular6 RxJS 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))的函数?

2 个答案:

答案 0 :(得分: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,则可以知道该函数的签名是什么

答案 1 :(得分:0)

如果我对您的问题的理解正确,并且您想向结果数组中的每个项目添加一个字段,然后将每个字段分别传递给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运算符,作为另一个答案。

相关问题