【发布时间】:2020-06-16 06:06:11
【问题描述】:
我正在使用 ngx 图表库来显示条形图。当我使用静态数组时它工作正常,但当我尝试动态填充它时,它不起作用。
以下是我的代码:
注意:allProducts 是一个从 API 返回的数组,其中包含 itemName、AmountPaid、Date 购买等列表。我只需要下面带有 itemname 和 amountpaid 的数组来使用 ngxChart 填充条形图。
当我使用这个静态数组时,一切正常:
this.products = [{
"name": this.allProducts[0].itemName,
"value": this.allProducts[0].AmountPaid
},
{
"name": this.allProducts[1].itemName,
"value": this.allProducts[1].AmountPaid
}
,
{
"name": this.allProducts[2].itemName,
"value": this.allProducts[2].AmountPaid
}
,
{
"name": this.allProducts[3].itemName,
"value": this.allProducts[3].AmountPaid
}
,
{
"name": this.allProducts[4].itemName,
"value": this.allProducts[4].AmountPaid
}
,
{
"name": this.allProducts[5].itemName,
"value": this.allProducts[5].AmountPaid
}
];
当我尝试如下动态创建它时 - 它不会以正确的格式返回数组:
this.allProducts.forEach((item) => {
this.productData.push({
"name": item.itemName,
"value": item.grossAmountPaid
});
})
静态数组的 console.log 返回以下 - 正确格式:
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "Car-SL-Monthly", value: 1000000}
1: {name: "Car-SL-Yearly", value: 1000000}
2: {name: "Car-RB-Monthly", value: 5000}
3: {name: "dsaf", value: 455}
4: {name: "Delivery Van", value: 500000}
5: {name: "Lorry", value: 1000000}
length: 6
__proto__: Array(0)
动态数组返回以下 - 格式不正确:
Array(6)
0: {name: "Car-SL-Monthly", value: 1000000}
1: {name: "Car-SL-Yearly", value: 1000000}
2: {name: "Car-RB-Monthly", value: 5000}
3: {name: "dsaf", value: 455}
4: {name: "Delivery Van", value: 500000}
5: {name: "Lorry", value: 1000000}
length: 6
__proto__: Array(0)
我的 foreach 循环有什么问题,如何让我的动态数组(使用 foreach)与静态数组的格式相同?
【问题讨论】:
-
格式正确/不正确是什么意思?两个输出的数据相同。
-
@KaustubhBadrike 我同意,但看看第一行 - 它似乎有不同的标题。
-
也许你应该停止依赖控制台日志的格式
标签: angular typescript ngx-charts