Home > Software design >  Handle multiple response types for nested api calls with different responses
Handle multiple response types for nested api calls with different responses

Time:12-08

I have two api calls which return different responses. These responses are strongly typed into TestData1Res and TestData2Res. How do I specify the response could be one of either and then process the property

`TestData1Res{ testData: string }

TestData2Res{ data: string }

this.getData1().pipe(catchError(error => this.getData2()))
  .subscribe(
    (res: TestData1Res|TestData2Res) => {
      if (res.testData) { //error 'Property 'testData' does not exist on type 'TestData1Res | TestData2Res'
      }
      if (res.data) { //error 'Property 'data' does not exist on type 'TestData1Res | TestData2Res'
      }
    }
  );`

CodePudding user response:

It may helpful to use dynamic data type

    this.getData1().pipe(catchError(error => this.getData2()))
  .subscribe(
    (res: any) => {
      if (res["testData"]) { 
      }
      if (res["data"]) { 
      }
    }
  );

CodePudding user response:

if you want to call one API call after getting response of another

this.getData1().subscribe(data => {
    // success getdata1
    this.getData2().subscribe(data => {
        //success getdata2
    }, err => {
        // getdata2 error
    }) 
}, err => {
    //getdata1 error
})

if you want to call both at once, you can use forkjoin from rxjs

forkjoin([this.getData1(), this.getData2()]).subscribe(result => {
    // result[0] - getdata1 result
    // result[1] - getdata2 result
}, err => {
    // err if something goes wrong
})
  • Related