angularmoltin

forEach angular loop


data:(4) [{…}, {…}, {…}, {…}]
included:{brands: Array(2), main_images: Array(4)}

I am currently logging that to the console. However within data is my products name and within included in my products href to their respective images.

In my .ts file:

 getAllProducts() {
    this.mhttp.allProducts()
      .subscribe((data: any) => {
        this.names = data.data;
        this.products = data.included.main_images;
        console.log(data);
      },
        error => {
          console.log(error);
        });
  }

in my html file:

<div class="row">
    <div class="col-sm-12">
      <div class="row">
        <div class="col-sm-4 products" *ngFor="let product of products">
          <div class="image">
            <img [src]="product.link.href">
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-sm-4 products" *ngFor="let name of names">
          <div class="name">
            <a routerLink="/product/viewProduct/{{name.id}}">
              <h3>{{ name.name | uppercase }}</h3>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>

at the moment I am looping through my images and them my product names, so the product names are not underneath they product images.

It came to my attention that forEach loops will be best. But I am not 100% sure how to forEach loop through different objects.


Solution

  • I know this question was asked long ago, but after reviewing my questions ond stackoverflow I remembered the solution was to map the two objects into one:

    getAllProducts() {
        this.mhttp.allProducts()
          .subscribe((data: any) => {
            this.products = data;
            this.prodList = this.products.data.map((itm, i) => {
              return {
                title: itm.name,
                imgUrl: this.products.included.main_images[i].link.href,
                price: itm.meta.display_price.with_tax.formatted,
                id: itm.id
              };
            });
            console.log(this.products);
          },
            error => {
              console.log(error);
            });
      }