【发布时间】: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。