简体   繁体   中英

How can I get values from two observables sequentially?

I'm a newbie with 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.

When I subscribe, I would like get both values : building and 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:

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

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]) => {
    // ...
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM