[英]rxjs forkJoin nested observable inside another observable
有两组可观察的(网络请求)。 在第一个 observable 解决后,我需要forkJoin
多个 observable。 但作为回报,我得到的是Subscriber
而不是数据。
请检查第三小提琴https://stackblitz.com/edit/zj3mhp?file=index.ts
import { forkJoin, of, timer } from "rxjs";
import { map } from "rxjs/operators";
let array = [of({ data: [1] }), of({ data: [2] })];
const init = of({ pages: 2 });
function gerData() {
const observable = forkJoin(array);
return init.pipe(
map(data => {
return observable.subscribe(data => {
const arr = [];
data.forEach(x => {
arr.push(...x.data);
});
console.log('array', arr);
return arr;
});
})
);
}
gerData().subscribe((data) => {
console.log('final data: ', data);
})
您可以使用mergeMap()
而不是 map(),返回订阅无济于事。
我们在map()
中返回的任何内容都将是订阅成功回调中收到的值。 我们无法从订阅对象中检索值。
在mergeMap
我们返回一个 Observable,它将与父 observable 合并,我们可以使用单个订阅获取合并的 observable 的值。
import { forkJoin, of, timer } from "rxjs";
import { map, mergeMap } from "rxjs/operators";
let array = [of({ data: [1] }), of({ data: [2] })];
const init = of({ pages: 2 });
function gerData() {
const observable = forkJoin(array);
return init.pipe(
mergeMap(data => {
return observable.pipe(map(data => {
const arr = [];
data.forEach(x => {
arr.push(...x.data);
});
console.log('array', arr);
return arr;
}));
})
);
}
gerData().subscribe((data) => {
console.log('final data: ', data);
})
你可以做类似的事情
function gerData() {
const observable = forkJoin(array);
return init.pipe(
switchMap(() => observable),
map(res => res.reduce((prev, next) => prev.concat(next.data), []))
);
}
gerData().subscribe(data => {
console.log("final data: ", data);
});
一旦您订阅了一个observable
它就会开始执行并变成一个subscription
,您应该返回observable
并使用switchMap
来运行该 observable。 请尝试以下操作:
function gerData() {
return init.pipe(switchMap(data=>
forkJoin(array).pipe(map(arr=>arr.map(item=>item.data)))
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.