问题描述
我使用 forkJoin 将两个可观察数组连接在一起:
connect(): Observable<any[]> {
this.userId = this.authService.userId;
this.habits$ = this.habitService.fetchAllById(this.userId);
this.status$ = this.statusService.fetchAll();
this.joined$ = forkJoin([this.habits$,this.status$]).pipe(
map(([habits,statuses]) =>
habits.map(habit => ({
...habit,status: statuses.find(s => s.habitId === habit.habitId)
})))
);
console.log(this.joined$);
return this.joined$;
在我的映射函数中,我将每个习惯可观察的习惯 ID 映射到状态可观察的习惯 ID。
哪个工作正常。问题是,我的 status$-Oberservable 中有多个对象,我想将它们映射到一个惯用 $-Oberservable 的一个惯用 ID。如何做到这一点?
解决方法
而不是使用 find
,它从数组中返回单个项目。您可以使用 filter
返回满足指定条件的所有项目的数组:
map(([habits,statuses]) =>
habits.map(habit => ({
...habit,statuses: statuses.filter(s => s.habitId === habit.habitId)
})))
,
你快到了。只需使用过滤器而不是查找。 filter 运行到数组的末尾,并在每个项目上调用它的回调;与 find 哪个在找到一个后停止相反。
connect(): Observable<any[]> {
this.userId = this.authService.userId;
this.habits$ = this.habitService.fetchAllById(this.userId);
this.status$ = this.statusService.fetchAll();
this.joined$ = forkJoin([this.habits$,this.status$]).pipe(
map(([habits,status: statuses.filter(s => s.habitId === habit.habitId)
})))
);
console.log(this.joined$);
return this.joined$;