我遇到以下情况,我获取父数据数组,然后对于每个父数据,发出另一个 http 请求来获取子数据。这工作正常,但父数据当然首先到达,然后子数据在一秒钟后返回。有什么方法可以返回一个只有在 parent 和 child 的所有数据到达后才会发出的单个可观察值?
return http.get('parent').map(parents => {
return parents.map(parent => {
parentData: parent.data
child: http.get('child').map(children => {
childrenData: children.data
})
})
});
编辑:工作解决方案
const result = this.http.get('https://jsonplaceholder.typicode.com/users').mergeMap((parents: any) => {
const getParentChild = p => {
return this.http.get('https://jsonplaceholder.typicode.com/users').first().map((c: any) => {
return {
parent: p,
child: c
}
});
};
return Observable.forkJoin(parents.map(p => getParentChild(p)));
});
result.subscribe(results => {
console.log(results);
});
最佳答案
正如 @Hugo Novo 上面提到的,forkJoin()
可能是最好的运算符。该运算符接受单个可观察值作为参数,或可观察值数组。
请注意,您还需要 mergeMap()
。当我们的 map 代码返回一个可观察对象本身时,我们希望发出最后一个可观察对象发射,而不是可观察对象本身。
- forkJoin():当所有子项完成时,返回为每个可观察对象发出的最后一项;
- mergeMap():当所有子项完成时,映射并返回每个父项及其子项;
const parent$ = Rx.Observable.of([1, 2, 3].map(i => ({
id: i,
name: 'parent ' + i
})));
const child = (i) => Rx.Observable.of({
id: i,
name: 'child ' + i
});
const result = parent$.mergeMap(parents => {
const getParentChild = p => child(p.id).map(c => {
return {
parent: p,
child: c,
};
});
return Rx.Observable.forkJoin(parents.map(p => getParentChild(p)));
});
result.subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.js"></script>
关于javascript - 从父级和子级 Http 请求获取可观察数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612984/