Dunguyen
Dunguyen

Reputation: 81

make synchronous HTTP calls in Angular 11

I created a service to get product details from product id like the following:

public async getXeViaId(id_xe:string)
{
  const path =`${this.apiServerURL}/xe/get_xe_via_id?id_product=${id_xe}`;
  const result = this.http.get(path).toPromise();
  return result;
}

Then I test like the following

this.xeService.getXeViaId("XE1700000082").then(value=>{console.log(value)});

Then it work fine but when I try with for loop like the following:

cart:any[]=[]
for(let i =0;i<3;++i)
    {
      let product:any
      this.xeService.getXeViaId("XE1700000082").then(value=>{product=value});
      this.cart.push(product)
    }

When I debug I realize that the cart push value null,its meaning value of product that I received is null.

How I can wait until HTTP request of one for loop is finished and then push it to cart. I tried to solve it using Promise and many way that use Promise to solve that problem but none of them worked fine. Can you guys fix it help me.It take a lot of my time

Upvotes: 1

Views: 641

Answers (2)

FolabiAhn
FolabiAhn

Reputation: 526

You are pushing a null because you do not wait the end of the execution of your promise.

You need to use async/await to achieve this.

const cart = [];
for(let i = 0; i < 3; ++i) {
  cart.push(
    await this.xeService.getXeViaId("XE1700000082")
  );
}

And don't forget to add async on your calling method.

Upvotes: 0

Evert
Evert

Reputation: 99776

const cart = [];
for(let i =0;i<3;++i) {
  cart.push(
    await this.xeService.getXeViaId("XE1700000082")
  );
}

Upvotes: 2

Related Questions