简体   繁体   English

如何使用带条件的 ConcatMap 进行多个 API 调用

[英]How to make multiple API calls using ConcatMap with conditions

In Angular 7, I am trying to invoke two different API methods sequentially.在 Angular 7 中,我试图按顺序调用两个不同的 API 方法。 If first one is successful then need to call second API method.如果第一个成功,则需要调用第二个 API 方法。

If first API response code is 500 internal server error then second API should not be invoked.如果第一个 API 响应代码是 500 内部服务器错误,则不应调用第二个 API。 Also I need to handle errors for each API calls.我还需要处理每个 API 调用的错误。

I tried Promise, async and await approach but when I check in developer tools, could see second one is invoked even if first API does not return any response.我尝试了 Promise、async 和 await 方法,但是当我检查开发人员工具时,即使第一个 API 没有返回任何响应,也可以看到调用了第二个。

Can someone please help me to achieve this using concatmap or any other Angular approach.有人可以帮助我使用 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;
    }
  }

You can use switchMap to accomplish this.您可以使用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);
  } 
)

Update : You can, of course, do some logic inside your switchMap更新:当然,您可以在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);
   })
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM