Home > other >  Action after push elements in array
Action after push elements in array

Time:08-18

I have implemented a function that I use to call an api, recover for each product some info and push into array. After that I have done this for all products, I would to do a action with the array.

So I have:

newProducts: any = []

 loadOfferRelated(offer) {
    // consider this offer with 2 products array.
    let products = offer.products
    for (let i = 0; i < products.length; i  ) {
    let apiCall = this.offerService.apiCall(products[i].id, product.catalogId)
    apiCall.pipe(untilDestroyed(this)).subscribe(
       (data) => { operationOnArray(data, products[i])}
     )
   }
   if(this.newProducts.length > 0){
   // ---> Here i should call another function but it doesn't enter there)
  }

 operationOnArray(data, product){
   // I make some operation product and save in array
  this.newProducts.push(products)
  console.log("this.newProducts", this.newProducts) <-- this is every for populated   1
  return
 } 

I have a problem to call the if when the array newProducts is populated, how can I do?

CodePudding user response:

Your problem is that whatever happens in you subscription is asynchronous. That means that your if is triggered before your request has ended, so it's most likely that your if condition will always end with a false.

CodePudding user response:

Ok so you can use a forkJoin, to make the api calls simultaneously and use the map operator to return each transformed element, push the returned data into the array and then finally call the if condition.

    newProducts: any = [];

    loadOfferRelated(offer) {
        // consider this offer with 2 products array.
        let products = offer.products;
        const apiCalls = products
            .map((product: any) => this.offerService.apiCall(product.id, product.catalogId))
            .pipe(
                map((data: any, i: number) => {
                    // i am not sure what your doing with the api call (data) so I am merging product and data, you customize
                    // to your requirement
                    return { ...products[i], ...data };
                })
            );
        forkJoin(apiCalls).subscribe((newProducts: Array<any>) => {
            this.newProducts = newProducts;
            if (this.newProducts.length > 0) {
                // ---> Here i should call another function but it doesn't enter there)
            }
        });
    }
  • Related