简体   繁体   中英

How to call two consecutive rest api in typescript?

I am new to typescript. I am facing the below mentioned problem. My scenario is, I have to call two consecutive REST APIs. If get success message from first one, then only I will call the second API. If both are successful, I will return success message, or required to return error message.

My two rest response structure are same. That is :-

{
  "timestamp" : "0654848"
  "status" : 200,
  "error" : "Error/Success" 
  "message" : "Failure/Success",    
  "path" : "api/v1/..", 
  "data" : "{}"
}

Call is initiating in the below mentioned way in account-form.component.ts file.

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 file :-

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

Other URL is /api/account/balance , which is a get call. I expect : -

1> If response from 1st api gets error -> Return error message of first

2> If response from 1st is correct, but from second gets some error -> Return error message of second

3> If response from both are success -> Return success message of the second

I have resolver the scenario in the below mentioned way.

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);
      }
    },
        );

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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