首页 > 解决方案 > forEach 角循环

问题描述

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

我目前正在将其记录到控制台。但是,在数据中是我的产品名称,并且在我的产品中包含在它们各自图像的 href 中。

在我的 .ts 文件中:

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

在我的 html 文件中:

<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>

目前我正在循环浏览我的图片和产品名称,因此产品名称不在产品图片下方。

我注意到 forEach 循环将是最好的。但我不是 100% 确定如何 forEach 循环遍历不同的对象。

标签: angularmoltin

解决方案


您可以使用类似下面的方法将它们组合成一个数组。

   getAllProducts() {
    this.mhttp.allProducts()
      .subscribe((data: any) => {
        this.products = data;
        this.productList = this.products.data.map(product => {
        //get the image id out of the product object
          const imageId = product['relationships'].main_image
            ? product['relationships'].main_image.data.id
            : false
            //now loop through and match them to the included data
           return {
            ...product,
            //id from product id to the the id of the included then add to product
            image: imageId
              ? this.productIncluded['main_images'].find(img => img.id === imageId).link.href
              : '/static/cat.svg'
            }
          }),
    error => {
      console.log(error);
        });
     }

然后在您的 html 中,所有内容都应该在要使用的产品列表数组中。


推荐阅读