how to manage data from request inside request loop

0

Issue

I’m using WooCommerce v3 api, my goal is to show a list with all the categories and horizontally show all the products by category, like:

Category name:
product product1 product2

Category 2 name:
product product1 product2

but there is not endpoint to get all this, so I get all the categories first with

  getAllCats(): Observable<any>{
    const req = this.httpS.get(`${API.prod.url+API.prod.woo+'products/categories/?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret}`);
    return req;
  }

  getProductsByCat(catId: number): Observable<any>{
    const req = this.httpS.get(`${API.prod.url+API.prod.woo+'products?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret+'&category='+catId}`);
    return req;
  }

and then on my component I am doing this

categories: any = {};
  cats: Array<any> = [];
  products: Array<any> = [];
  catsWithAllProducts: any = {
    category: [{
      products: []
    }]
  };
  kats: Category[] = [];



showAllCatsWithProducts(){
    this.pService.getAllCats().subscribe((cats) => {
      for (const [i,cat] of cats.entries()) {
        this.pService.getProductsByCat(cat.id).subscribe((products) => {
          this.cats.push(cat);
          this.products.push(products);
          this.catsWithAllProducts.category = cat;
          this.kats.push(this.catsWithAllProducts); //new categories array with products
        });
      }
    });
  }

I have two problems, the products[] is empty, I’m confused with, how to achieve to create a new object or array or array of objects with all the products inside a category. Right what is printed on screen is all the categories but with repeated name:

enter image description here

I have 10 categories, and it shows the first name that receives * the number of categories. What I’ve been thinking is that first it should be async, I mean is an observable but it is pushing to the array each element with or without response yet. I’m kind of stuck here, thanks for reading me.

Solution

I handle it with async/await and changing the regular for to forEach at showAllCatsWithProducts() method

  async showAllCatsWithProducts(){
    this.pService.getAllCats().subscribe((cats) => {
      cats.forEach(async cat => { //for each category
        const response = await this.pService.getProductsByCat(cat.id).subscribe(res => { //It's gonna wait por their products
          this.categories.push({id: cat.id,name: cat.name,slug:cat.slug, products: res}); //Push category with products
        });
      });
    });
  }

Answered By – Rowe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More