How to make sequential service call on success of first service response in Angular

Viewed 451

I need to make multiple service call in angular one after other. need to pass the first service call respose as input to another service.

Here is my component:

 Demo(): any {
        if (fileToUpload) {
          this._voiceboxService.upload(fileToUpload)
          .subscribe((res: any) => {
            this.text=res.prediction
              console.log(res);
          });
      }
      else
          console.log("FileToUpload was null or undefined.");
    }
}

Here is my Service: i need to call all three service on success of one service and need to pass first service resposnse as input for next service

          upload(fileToUpload: any) {
            let input = new FormData();
            input.append("file", fileToUpload);
           return this.http.post<any>('https://localhost:5001/', input)
         
          language(data: any) {
           return this.http.post<any>('https://localhost:5002', data)
          }
    
        getDetails(data: any) {
           return this.http.post<any>('https://localhost:5003', data)
          }
2 Answers

Use mergeMap. I assume you want to do this in your component:

   this._voiceboxService.upload(fileToUpload).pipe(mergeMap(upload => 
       this._voiceboxService.language(upload)
          .pipe(mergeMap(language => this._voiceboxService.getDetails(language))
   ))).subscribe((res: any) => {
        this.text=res.prediction
        console.log(res);
   });

You can use map in the end organize your final value result.

You could use any of the RxJS higher order mapping operators like switchMap to map from one observable to another. You could find differences between different mapping operators here.

Service

upload(fileToUpload: any) {
  let input = new FormData();
  input.append("file", fileToUpload);
  return this.http.post<any>('https://localhost:5001/', input).pipe(
    switchMap(res => this.language(res)),  // <-- `res` = response from previous request
    switchMap(res => this.getDetails(res)) // <-- `res` = response from `this.language()`
  );
}

language(data: any) {
  return this.http.post<any>('https://localhost:5002', data)
}

getDetails(data: any) {
  return this.http.post<any>('https://localhost:5003', data)
}

Component

Demo(): any {
  if (fileToUpload) {
    this._voiceboxService.upload(fileToUpload).subscribe({
      next: (res: any) => {                // <-- `res` = response from `getDetails()`
        this.text = res.prediction
        console.log(res);
      },
      error: (error: any) => {
        // handle errors
      }
    });
  } else {
    console.log("FileToUpload was null or undefined.");
  }
}
Related