【问题标题】:How to make multiple API calls using ConcatMap with conditions如何使用带条件的 ConcatMap 进行多个 API 调用
【发布时间】:2021-03-04 13:48:06
【问题描述】:

在 Angular 7 中,我尝试按顺序调用两种不同的 API 方法。如果第一个成功则需要调用第二个 API 方法。

如果第一个 API 响应代码是 500 内部服务器错误,则不应调用第二个 API。我还需要处理每个 API 调用的错误。

我尝试了 Promise、async 和 await 方法,但是当我签入开发人员工具时,即使第一个 API 没有返回任何响应,也可以看到调用了第二个。

有人可以帮助我使用 concatmap 或任何其他 Angular 方法来实现这一点。

public fetchandUpdate() {
    this.isSuccess= false;
    this.errorMessage = "";
    this.displayMessage = false;

     // First API call
      this.myService.getUserDetails(this.userid)
      .subscribe(
        (response) => {                           
          console.log('response received')
          this.userdetails= response;
        },
        (error) => {                              
          console.error('error caught in fetching user details')
          this.errorMessage = error;
          this.isSuccess= false;
        }
      )

    // Need to call this only if first API's response http status code is not 500
   if(firstAPIresponse.statuscode != 500)
   {
    this.myService.updateUserDetails(this.userdetails)
          .subscribe(
            (response) => {                           
              console.log('response received')
              this.isSuccess= true;
            },
            (error) => {                              
              console.error('error caught in updating user details')
              this.errorMessage = error;
              this.isSuccess= false;
            }
          )
      

     // This value should be updated only if above two is successful
      this.displayMessage=true;
    }
  }

【问题讨论】:

  • 您可能想尝试通过 switchMap 进行管道传输,或者转换为 promise 并等待它们。目前您正在并行运行调用,因此没有机会使用第一个数据,也没有条件执行
  • @Michael 你能分享这个场景的任何示例 URL。

标签: angular rxjs angular7


【解决方案1】:

您可以使用switchMap 来完成此操作。

// First API call
this.myService.getUserDetails(this.userid).pipe(
  // Logging is a side effect, so use tap for that
  tap(res => console.log('First API success', res)),
  // Call the second if first succeeds
  switchMap(resultFromUserDetails => this.myService.updateUserDetails(this.userdetails).pipe(
    // Handle your error for second call, return of(val) if succeeds or throwError() if you can't handle it here
    catchError(err => { 
      console.log('Error for second API (you can use statusCode here)', err);
      return of(); 
    }),
    // Logging is a side effect, so use tap for that
    tap(res => console.log('Second API success', res)),
  )),
  
  // Handle your error for first call, return of(val) if succeeds or throwError() if you can't handle it here
  catchError(err => { 
    console.log('Error for first API (you can use statusCode here)', err);
    return of(); 
  }) 
).subscribe(
  // handle both successfull
  resultFromUpdateUserDetails => {
    console.log('Both APIs succeeded, result from 2) is returned', resultFromUpdateUserDetails);
  },
  // handle uncaught errors
  err => {
    console.log('Any error NOT handled in catchError() or if you returned a throwError() instead of of() inside your catchError(), err);
  } 
)

更新:当然,您可以在switchMap 中执行一些逻辑

this.myService.getUserDetails(this.userid).pipe(
   switchMap(res => {
     // do something with res, or other logic here

     // make sure to return your new observable at the end
     return this.myService.updateUserDetails(this.userdetails);
   })
);

【讨论】:

  • 我无法理解错误处理部分。您能否用 console.log('error') 或 (console.log('success') 为每个部分更新答案。这将非常有帮助。
  • 另外,是否可以在switchMap之前使用if逻辑。
  • 我还可以从第一个 API 响应中检查内部服务器错误状态代码。
  • 更新了我的答案。是的,可以在 switchMap 中使用逻辑。只要确保在最后返回一个新的 observable 即可。您可以检查 catchError() 中的 errorCode。它得到了与订阅中的第二个回调中相同的错误。
猜你喜欢
  • 2020-10-06
  • 1970-01-01
  • 2021-10-24
  • 2019-11-16
  • 2021-11-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多