[英]How to map two Oberservable arrays based on a value?
I have two observable arrays.我有两个可观察的 arrays。
habits$: Observable<Habit[]>;
status$: Observable<Status[]>;
The habit has the following structure:该习惯具有以下结构:
export interface Habit {
habitId: number;
name: string;
repeatVal: number;
notification: string;
color: string;
question: string;
id: number;
}
The status array has the habitId, date and status as keys.状态数组有 habitId、日期和状态作为键。
I want to merge both habits$ and status$ into one Observable array based on the habitId attribute present in both of them.我想根据两者中存在的habitId 属性将habits$ 和status$ 合并到一个Observable 数组中。
I have done some research and a combination of mergeMap() and forkJoin() seems to be the way to go, like shown here Combine multiple observable arrays into new object array我已经做了一些研究,mergeMap() 和 forkJoin() 的组合似乎是通往 go 的方法,如下所示将多个可观察的 arrays 组合成新的 ZA8CFDE6331BD59EB2AC96F8911C4B6 数组
But I can't figure out a syntax that will work for me.但我想不出适合我的语法。
This is how my code looks at the moment:这就是我的代码目前的样子:
ngOnInit() {
this.habits$ = this.habitService.fetchAllById(this.authService.userId);
console.log(this.habits$);
this.status$ = this.statusService.fetchAll();
this.habits$.pipe(
mergeMap(habits => {
this.status$ = this.statusService.fetchAll().filter(status => status.habitId == habits.habitId);
}));
console.log(this.joined$);}
I would use forkJoin in the following fashion:我会以下列方式使用 forkJoin:
ngOnInit() {
forkJoin([
this.habitService.fetchAllById(this.authService.userId),
this.status$ = this.statusService.fetchAll()
]).subscribe(([habits, statuses]) => {
this.joined = habits.map(habit => ({
...statuses.find(t => t.habitId === habit.habitId),
...habit
}));
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.