[英]How can I get values from two observables sequentially?
I'm a newbie with RxJs.我是 RxJs 的新手。
My purpose is : (1) make a first call backend and get value, then (2) based on the returned value, make an other call backend and return both values as an array.我的目的是:(1)首先调用后端并获取值,然后(2)根据返回的值,进行另一个调用后端并将两个值作为数组返回。
When I subscribe, I would like get both values : building and buildingUnit.当我订阅时,我希望获得两个值:building 和 buildingUnit。
This is the way of I trying to achieve this purpose :这是我试图实现这一目的的方式:
this._buildingsService.loadBuilding(1).pipe(
mergeMap((b: Building) => {
if (b) {
return this._buildingUnitsService.loadBuildingUnit(b);
}
})
).subscribe((bu: BuildingUnit) => {
});
The kind of result that I would like to get back :我想得到的那种结果:
this._buildingsService.loadBuilding(1).pipe(
mergeMap((b: Building) => {
if (b) {
return this._buildingUnitsService.loadBuildingUnit(b);
}
})
).subscribe((b: Building, bu: BuildingUnit) => {
});
Thank you谢谢
You could use forkJoin
to pass both values back:您可以使用
forkJoin
将两个值传回:
this._buildingsService.loadBuilding(1).pipe(
mergeMap((b: Building) => forkJoin({
b: of(b),
bu: b ? this._buildingUnitsService.loadBuildingUnit(b) : of(null)
}))
).subscribe((result: { b: Building, bu: BuildingUnit }) => {
});
DEMO: https://stackblitz.com/edit/angular-p5vtej演示: https : //stackblitz.com/edit/angular-p5vtej
You can just map the second value into an array.您可以将第二个值映射到数组中。
this._buildingsService.loadBuilding(1).pipe(
mergeMap((b: Building) => {
if (b) {
return this._buildingUnitsService.loadBuildingUnit(b).pipe(
map(c => [b, c]),
);
}
return of([b]); // or `[b, undefined]` to be more obvious
})
.subscribe(([b, c]) => {
// ...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.