如何让这个 forkJoin 返回一个 observable-array 而不是订阅?
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$
]).subscribe(([habits, statuses]) => {
this.joined = habits.map(habit => ({
...statuses.find(t => t.habitId === habit.habitId),
...habits
}));
});
return this.joined$;
}
目前我的变量定义如下:
export class HabitDataSource extends DataSource<any> {
userId: Pick<User, 'id'>;
habits$: Observable<Habit[]>;
status$: Observable<Status[]>;
joined$: Subscription;
joined: any[];
但是 connect() 方法需要一个 Observable-Array。
答案 0 :(得分:4)
如何让这个 forkJoin 返回一个 observable-array 而不是订阅?
forkJoin
确实返回数组。您得到 Subscription
的原因是因为您正在调用 .subscribe()
。
您可以使用 map
运算符,而不是在 subscribe 内部执行映射逻辑:
connect(): Observable<any[]> {
this.userId = this.authService.userId;
this.habits$ = this.habitService.fetchAllById(this.userId);
this.status$ = this.statusService.fetchAll();
return forkJoin([this.habits$, this.status$]).pipe(
map(([habits, statuses]) =>
habits.map(habit => ({
...habit,
status: statuses.find(s => s.habitId === habit.habitId)
}))
)
);
}