首页 > 解决方案 > 将 API 调用中的对象格式化为 Google Charts 上的 dataTable 格式(ng2-google-charts)

问题描述

我正在使用ng2-google-charts在 Angular 10 项目中构建 geoChart。一切都适用于固定数据,我遇到的问题是我不确定如何格式化(和添加)来自 API 调用的数据。

这是我的 geoChart 属性,可以完美地处理固定数据

public geoChart: GoogleChartInterface = {
   chartType: 'GeoChart',    
   dataTable: [
     ['Country', 'Ice Machines'],
     ['Austria', 1],
     ['Belgium', 2],
     ['Bulgaria', 3],    
   ],
   options: {},
};

这是我从 API 收到的对象 (data.response) --> [{...}, {...}, {...}, {...}, {...}, {...}]

0: {paisCode: "DE", total: 1}
1: {paisCode: "DK", total: 1}
2: {paisCode: "ES", total: 1}
3: {paisCode: "FR", total: 1}
4: {paisCode: "NL", total: 1}
5: {paisCode: "RO", total: 1}
length: 6

这就是我正在尝试的:

data.response.forEach(element => {
   let countryCode = element.paisCode;
   let totalPerCountry = element.total;
   //formattedDataMap +=  "[" + "'" + countryCode +"'" + ',' + totalPerCountry + "],";
   this.geoChart.dataTable.push('[' + countryCode + ',' + totalPerCountry + ']')
   formattedDataMap.push('[' + countryCode + ',' + totalPerCountry + ']')
   //console.log(formattedDataMap);
})

但数据未正确添加:

0: (2) ["Country", "Total"]
1: (2) ["Austria", 1]
2: (2) ["Belgium", 2]
3: (2) ["Bulgaria", 3]
4: "[DE,1]"
5: "[DK,1]"
6: "[ES,3]"
7: "[FR,1]"
8: "[NL,1]"
9: "[RO,1]"

更新: 我已经更新了我的方法,但是数组没有任何反应。它的大小相同,具有相同的元素。

  async myMethod() {
     if (this.account.email) {
        (await this.myService.MyMethod())
        .pipe(first())
        .subscribe(async (data: any) => {        
           this.geoChart.dataTable.concat(                
             data.response.reduce((acc, curr) => {
             acc.push([curr['paisCode'], curr['total']]);
             return acc;
           }, [])
        ); 
        console.log(this.geoChart.dataTable);
    });       
   }
 }

标签: angularforeachng2-google-chart

解决方案


使用地图工作:

   data.response.map(item => {
      this.geoChart.dataTable.push([item.paisCode, item.total]);
   })

推荐阅读