angular - 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 循环遍历不同的对象。
解决方案
您可以使用类似下面的方法将它们组合成一个数组。
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 中,所有内容都应该在要使用的产品列表数组中。
推荐阅读
- mysql - Mysql加入json值问题
- c - 将带有指针的简短 ASM 片段翻译成 C 代码
- reactjs - 你如何在 React 中对 Realm-Web 中的查询结果进行排序?
- reactjs - Laravel-echo 显示 401(未经授权)的私人频道,除了一位用户
- gradle - 如何获取 gradle SourceSet 的目录?
- c++ - C++ STL 数组的迭代器大小
- javascript - 将 JavaScript UTC 日期时间转换为本地 YYYY-MM-DD
- jenkins - 如何使用“POST BUILD”部分中的 http POST URL 更新 Jenkins 中的 200 个作业。我可以编写一个 groovy 脚本来一次更新吗?
- python - Python Selenium 通过 xpath 查找并验证 ID
- azure - Azure 存储帐户文件共享内容保留期