I am calling 3 API's from angular, I want to wait API call until first API call is complete and return resu

50 Views Asked by At
if (article[0] === undefined) {
        this.saveArticle(this.quickExpense.ExpenseArticle);
      }

      if (supplier[0] === undefined) {
        this.saveSupplier(this.quickExpense.SupplierCode);
      }
      else{
        this.quickExpense.SupplierCode = supplier[0].value;
      }

      if ((article[0] !== undefined || this.isArticleSaved) && (supplier[0] !== undefined || this.isSupplierSaved)) {
        this.saveQuickExpense(this.quickExpense);
      }

Here article and supplier are list variables. I want to post article and supplier if not exists and after execution of these API's I want to assign result to this.quickExpense and then want to call saveQuickExpense. But currently before getting result of article and supplier API saveQuickExpense API is getting called.

2

There are 2 best solutions below

0
Naren Murali On

You need to subscribe to an observable to make it happen which makes it asynchronous, so you need to understand the difference between synchronous and asynchronous code.

console.log(1);
setTimeout(() => {
    Console.log(2);
});
console.log(3);

You would expect the output will be 123 but it's actually 132 because the code inside the setTimeout is asynchronous similarly is the case for your api calls, always synchronous code will execute followed by asynchronous code

So just call one api after another inside the subscribe block and this issue will disappear

(article[0] === undefined ? this.saveArticle(this.quickExpense.ExpenseArticle) : of({})).subscribe(() =>{ 
     if (supplier[0] === undefined) {
        this.saveSupplier(this.quickExpense.SupplierCode);
      }
      else{
        this.quickExpense.SupplierCode = supplier[0].value;
      }

      if ((article[0] !== undefined || this.isArticleSaved) && (supplier[0] !== undefined || this.isSupplierSaved)) {
        this.saveQuickExpense(this.quickExpense);
      }
      });

      
1
codewithharshad On

use promise and async/await like

your servicer look like

 getCustomMaterialList(payload: any) {
return this.http.post<any>(`${this.apiUrl}/CustomMaterial/GetCustomMaterialList`, payload).toPromise();

}

  async getData(){
const abc = await this.yourservice.getCustomMaterialList()
 console.log(abc);
}

this is only example of async/await