首页 > 解决方案 > Angular 9/10:根据类别显示产品数据

问题描述

我有来自 subscribe getAllProduct() 的数据显示在表中:

[{
    "productId": 1,
    "name": "Stuart UC152 Magnetic Stirrer",
    "description": "Stuart UC152 Magnetic Stirrer, max. capacity 15L, Ceramic",
    "isTaxable": true,
    "sku": "UC512                                             ",
    "preferredVendor": "2",
    "pictures": "assets/img/product/magnetic_stirrer.jpg",
    "productGroupId": 3
},
{
    "productId": 2,
    "name": "Dell SE2419HR 24\" ",
    "description": "Dell SE2419HR 24\" Full HD IPS Monitor (HDMI, VGA, 3 Yrs Wrty)",
    "isTaxable": true,
    "sku": "DELL123                                           ",
    "preferredVendor": "1008",
    "pictures": "assets/img/product/lcd_monitor.jpg",
    "productGroupId": 4
},
{
    "productId": 3,
    "name": "Dell PowerEdge T140 Tower Server",
    "description": "Dell PowerEdge T140 Tower Server (E-2124, 8GB, 1TB, H330 Raid Controller)",
    "isTaxable": true,
    "sku": "T140                                              ",
    "preferredVendor": "1008",
    "pictures": "assets/img/product/server.jpg",
    "productGroupId": 4
},
{
    "productId": 4,
    "name": "Lab Binocular Compound Microscope ",
    "description": "AmScope 40X-2500X LED Lab Binocular Compound Microscope with 3D-Stage",
    "isTaxable": true,
    "sku": "DBN450                                            ",
    "preferredVendor": "1",
    "pictures": "assets/img/product/microscope.jpg",
    "productGroupId": 3
}]

问题是当我尝试根据 productGroupId 在一个变量中将所有数据显示到单独的表中时。您可以从图像中看到所有产品都混合在一起,显示在两个表中,而不是根据 productGroupId 分开。谁能帮我理解如何让它显示在单独的桌子上?

在此处输入图像描述

标签: angularangular9angular10

解决方案


首先,您必须根据产品组 ID 将列表分成两个列表

//Considering all your products are inside variable this.products
let labEquipments = this.products.filter(product => product.productGroupId == 3);
let itTools = this.products.filter(product => product.productGroupId == 4);

然后使用这些各自的列表来显示您的表格

- 编辑 -

如果您有大量产品组并动态获取每个列表,您可以为相同的产品组创建一个函数

getProductsByGroup(productGroupId){
    return this.products.filter(product => product.productGroupId == productGroupId);
}

推荐阅读