【问题标题】:Handle multiple response types for nested api calls with different responses处理具有不同响应的嵌套 api 调用的多种响应类型
【发布时间】:2022-01-13 10:44:11
【问题描述】:

我有两个返回不同响应的 api 调用。这些响应被强输入到 TestData1Res 和 TestData2Res。如何指定响应可以是其中之一,然后处理属性

`TestData1Res{ 测试数据:字符串 }

TestData2Res{ 数据:字符串 }

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'
      }
    }
  );`

【问题讨论】:

  • 只有在调用getData1() 出错后才想调用getData2() 吗?
  • 您不应该以这种方式处理错误。如果出现错误,您应该返回一个空的 observable,然后使用 switchmap 调用您的服务 2。

标签: angular typescript observable


【解决方案1】:

使用动态数据类型可能会有所帮助

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

【讨论】:

    【解决方案2】:

    如果您想在获得另一个 API 调用后调用另一个 API 调用

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

    如果你想同时调用两者,你​​可以使用 forkjoin from rxjs

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多