[英]Convert array of observables of observables to array of observables rxjs
为了简化问题,我在这里使用了数字和字符串。 编码:
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>[]
如何从getStrings
函数获取Observable<string>[]
? 我曾尝试使用 flatMap、switchMap 但无法获得完美的组合。
您需要使用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))
因此,据我所知,您想通过 observable 将两个列表“压缩”在一起?
我可以给你这个
const numbers$: Observable<number[]> = of([1, 2, 3]);
const strings$: Observable<string[]> = of(['a', 'b']);
const combined$: Observable<any> = zip(numbers$, strings$)
.pipe(
map(([numbers, strings]) =>
numbers.length > strings.length ?
numbers.map((value, index) => [value, strings[index]]) :
strings.map((value, index) => [numbers[index], value]))
);
combined$.subscribe(value => console.log(value));
这将记录: [ [ 1, "a" ], [ 2, "b" ], [ 3, null ] ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.