forkJoin depending on another response in Angular

166 Views Asked by At

I have a switchMap and then a forkJoin but one of these calls depends on another one

this.route.paramMap
        .pipe(
          switchMap((params) => {
            let id = parseInt(params.get('id'));
            return forkJoin({
              tableDataDetail: this.tblService.getTableDataDetail(id),
              comboDetails: this.tblService.getUserComboDetails(// the id from the response of tableDataDetail),
            });
          })
        )
        .subscribe(
          ({ tableDataDetail, comboDetails }) => {
            this.data = tableDataDetail;
            this.comboDetails = comboDetails;   
          }
        )

as you can see, I need as params of the getUserComboDetails() service, a field from the response of the other one service (that is the tableDetailId). How can I do this in this way?

1

There are 1 best solutions below

2
On BEST ANSWER

if one obs need values from another you need use switchMap again

this.route.paramMap
  .pipe(
    switchMap(params => {
      let id = parseInt(params.get("id"));
      return this.tblService.getTableDataDetail(id).pipe(
        switchMap(tableDataDetail => {
          return this.tblService
            .getUserComboDetails(tableDataDetail.id)
            .pipe(
              map(details => ({
                tableDataDetail: tableDataDetail,
                comboDetails: details
              }))
            );
        })
      );
    })
  )

NOTE: You can in map, instead return an object return an array

this.route.paramMap.pipe(
      ...
                map(details=>([tableDataDetail,details]
                )
              )
           }
        )
      }))

So, you can, when subscribe use destructuring

   ....subscribe(res=>{
        [this.data,this.comboDetails]=res;
       })

Update I make a stackblitz and corrected typo syntax -missing some { or )