[英]Convert array of observables of observables to array of observables rxjs
To simplify the problem i have used numbers and strings here.为了简化问题,我在这里使用了数字和字符串。 The code:
编码:
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))
The error i am getting is: Type 'Observable<Observable<string>[]>' is missing the following properties from type 'Observable<string>[]
How can i get Observable<string>[]
from getStrings
function?我得到的错误是:
Type 'Observable<Observable<string>[]>' is missing the following properties from type 'Observable<string>[]
如何从getStrings
函数获取Observable<string>[]
? I have tried to use flatMap, switchMap but unable to get the perfect combination.我曾尝试使用 flatMap、switchMap 但无法获得完美的组合。
You'll need to use mergeMap()
and forkJoin()
:您需要使用
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 https://stackblitz.com/edit/rxjs-dzvsbh?file=index.ts
So as I understand you want to "zip" two lists together, via observable ?因此,据我所知,您想通过 observable 将两个列表“压缩”在一起?
I can offer you this one我可以给你这个
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));
This will log: [ [ 1, "a" ], [ 2, "b" ], [ 3, null ] ]这将记录: [ [ 1, "a" ], [ 2, "b" ], [ 3, null ] ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.