如何将映射值组合到可观察数组?

时间:2021-01-02 00:17:58

标签: rxjs

我有一个对象数组,我只需要从每个对象中获取 trainingName 和 numOfLikes。 我用 map 做到了这一点,但我想用没有 res.map 的 observables 做同样的事情:

this.postsService
      .fetchAll()
      .pipe(
        switchMap((res) =>
          of(
            res.map((post) => {
              return { trainingName: (post.trainingID as ITraining).name, numOfLikes: post.numOfLikes };
            })
          )
        )
      )
      .subscribe((res) => {
        this.data = res;
    }

尝试了以下方法:

this.postsService
      .fetchAll()
      .pipe(
        switchMap((res) => from(res)),
        mergeMap((post) => of({ trainingName: (post.trainingID as ITraining).name, numOfLikes: post.numOfLikes })),
        concatMap((res) => of(res)) 
// here I want to wait for all elements of the array to be transformed to the correct format and emit the completed array, but I get them one by one

我应该使用哪个运算符来以 rxjs 方式执行此操作?

1 个答案:

答案 0 :(得分:1)

下面的例子做了两件非常相似的事情。第一个使用 Array#map ,第二个使用 RxJS#map 来做同样的事情。打印从 2 到 7 的数字

from(
  [1,2,3,4,5,6].map(x => x + 1)
).subscribe(console.log);

from([1,2,3,4,5,6]).pipe(
  map(x => x + 1)
).subscribe(console.log);

一般来说,将数组转换为流然后再转换回数组有点代码味道。

但是,如果你无论如何都想这样做,你可以这样做:

这个:

this.postsService.fetchAll().pipe(
  map(res => res.map(post => ({ 
    trainingName: (post.trainingID as ITraining).name, 
    numOfLikes: post.numOfLikes 
  })),
).subscribe(res => this.data = res);

变成

this.postsService.fetchAll().pipe(
  switchMap(res => res),
  map(post => ({ 
    trainingName: (post.trainingID as ITraining).name, 
    numOfLikes: post.numOfLikes 
  })),
  toArray()
).subscribe(res => this.data = res);
相关问题