我有一个对象数组,我只需要从每个对象中获取trainingName和numOfLikes。我用map做到了这一点,但是我想在没有Observables的情况下做确切的事情res.map
:
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的方式执行此操作?
下面的示例做了两个非常相似的事情。第一个使用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句