Create angular method containing two rest calls and the second depending on the result from the first

Viewed 22

I'm need to create a function that contains two separate rest calls as data is needed to be passed from the first call to the second. How should this be structured within angular.

This code is basically what I need it to do but not sure how to structure or format.

  getInfo(CName: string, PName: string, Id: string): void {
    this.subscriptions.push(
      this.FindService.getG(CName, PName)
        .subscribe((details: data) => {this.data = details})
    )
    this.subscriptions.push(
      this.FindAdminService.getP(CName, PName, Id)
        .subscribe((details: Info) => {this.data = details})
    )
  }
1 Answers

If you have to do them at the same time :

getInfo(CName: string, PName: string, Id: string): void {

  forkJoin({
    details: this.FindService.getG(CName, PName),
    adminDetails: this.FindAdminService.getP(CName, PName, Id)
  }).subscribe(({ details, adminDetails }) => {
    // Do what you need here
  })

}

If you have to chain one after the other :

getInfo(CName: string, PName: string, Id: string): void {

  this.FindService.getG(CName, PName).pipe(
    switchMap(details => this.FindAdminService.getP(CName, PName, Id))
  ).subscribe(adminDetails => {
    // Do what you need here
  });
}
Related