为了简化问题,我在这里使用了数字和字符串。编码:
const numbers$:Observable<number[]> = of([1,2,3]);
const strings: string[] = ["a","b"];
function getStrings(): Observable<string>[]{
return numbers$.pipe(
map((numbers: number[]) => {
const strings$: Observable<string>[] = strings.map(s => of(s));
return strings$;
}),
)
}
getStrings().subscribe(x => console.log(x))
我得到的错误是:
Type 'Observable<Observable<string>[]>' is missing the following properties from type 'Observable<string>[]
如何从
Observable<string>[]
函数获取getStrings
?我尝试使用flatMap,switchMap,但无法获得完美的组合。Stackblitz
最佳答案
您需要使用mergeMap()
和forkJoin()
:
function getStrings(): Observable<string[]>{
return numbers$.pipe(
mergeMap((numbers: number[]) => {
const strings$: Observable<string>[] = strings.map(s => of(s));
return forkJoin(strings$);
}),
)
}
getStrings().subscribe(x => console.log(x))
https://stackblitz.com/edit/rxjs-dzvsbh?file=index.ts
关于javascript - 将可观察的观测值数组转换为可观察的数组rxjs,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60759998/