如何在typescript中调用两个连续的RESTAPI?
我是打字新手。我面临着下面提到的问题。我的场景是,我必须调用两个连续的RESTAPI。如果从第一个API获取成功消息,那么只有我会调用第二个API。如果两者都成功,我将返回成功消息,或者需要返回错误消息 我的两个rest-response结构是相同的。即:-如何在typescript中调用两个连续的RESTAPI?,typescript,rest,rxjs,Typescript,Rest,Rxjs,我是打字新手。我面临着下面提到的问题。我的场景是,我必须调用两个连续的RESTAPI。如果从第一个API获取成功消息,那么只有我会调用第二个API。如果两者都成功,我将返回成功消息,或者需要返回错误消息 我的两个rest-response结构是相同的。即:- { "timestamp" : "0654848" "status" : 200, "error" : "Error/Success&qu
{
"timestamp" : "0654848"
"status" : 200,
"error" : "Error/Success"
"message" : "Failure/Success",
"path" : "api/v1/..",
"data" : "{}"
}
调用以下面提到的方式在account form.component.ts文件中启动
verifyAccount(){
this.service.validate(this.accountModel).subscribe((resp: any) => {
if (resp.status = 200) {
this._router.navigate(['/home/accountPanel']);
this.toastr.success(resp.message);
}
else{
this.toastr.error(resp.message);
}
},
);
}
Service.ts文件:-
validate(account: Account): Observable<any> {
return this.http.post<any>(`${config.apiUrl}/api/account/validate`, JSON.stringify(user))
.pipe(
**---Help Required in this portion---**
catchError(error => {
console.log(error);
return response;
}));
}
验证(账户:账户):可观察{
返回此.http.post(`${config.apirl}/api/account/validate`,JSON.stringify(用户))
.烟斗(
**---这部分需要帮助---**
catchError(错误=>{
console.log(错误);
返回响应;
}));
}
另一个URL是/api/account/balance,这是一个get调用。
我期望:-
1>如果第一个api的响应出现错误->返回第一个api的错误消息
2>如果第一个的响应正确,但第二个的响应出现一些错误->返回第二个的错误消息
3>如果来自两个的响应都成功->返回第二个的成功消息我以下面提到的方式解决了该场景
verifyAccount(){
this.service.validate(this.accountModel).subscribe((res : any) => {
if (res.status == 200) {
this.service.getBalance(res).subscribe((resp : any) => {
if (resp.status == 200) {
}
else{
this.toastr.error(resp.error);
}
});
}
else{
this.toastr.error(res.error);
}
},
);
}
您可以使用或可管道运算符。我正在尝试找出,如何使用它来解决我的问题。如果您有用于rest调用的concatMap()示例的任何链接,请提供。本文可能会有所帮助:
switchMap
、mergeMap
和concatMap