每个角度环

时间:2018-08-22 15:07:31

标签: angular moltin

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遍历不同的对象。

2 个答案:

答案 0 :(得分:0)

您可以使用如下所示的方法将它们组合成一个阵列。

   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中,所有内容都应在要使用的产品列表数组中。

答案 1 :(得分:0)

我知道这个问题是很久以前提出的,但是在回顾了我的问题和stackoverflow之后,我记得解决方案是将两个对象映射为一个:

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);
        });
  }