angular-google-charts:意外值NaN解析x属性

时间:2019-02-23 19:01:57

标签: angular angular-material google-visualization nan

我有一个Angular 6服务,该服务传递数据以填充Google物料图。

app.component.ts

  export class CustomersComponent implements OnInit {

  customers: Customer[];

  charts: Array<{
    title: string,
    type: string,
    data: Array<Array<string | number | {}>>,
    roles: Array<{ type: string, role: string, index?: number }>,
    columnNames?: Array<string>,
    options?: {}
   }> = [];

  @ViewChild('chart')
  chart: GoogleChartComponent;

  constructor(private customerService: CustomerService) {}

ngOnInit(): void {
 this.getCustomers();
 this.customerService.getCustomers()
 .subscribe(res => {
  //  console.log(res)
   let firstname = res.map(res => res.firstname);
   console.log(firstname)
   let age = res.map(res => res.age);
   console.log(age)

   this.charts.push({
    title: 'Customer Demographics',
    type: 'Bar',
    columnNames: ['Customer', 'Age'],
    roles: [],
    data: [
      [firstname, age],
    ],
    options: {
      chart: {
        title: 'Customer Demographics',
        subtitle: 'Sales, Expenses, and Profit: 2014-2017'
      },
      bars: 'vertical' // Required for Material Bar Charts.
    }
  });
 })}

然后,当我尝试将数据传递到Google图表时,没有任何填充,并且我得到了意外值NaN解析x属性错误。

enter image description here

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

数据似乎格式错误。

代替具有单独列值的两个数组...

[ "Joe", "Peter", "Lauren"...
[ 36, 18, 31...

数据中的每一行都应该是一个具有每个列值的数组...

[ "Joe", 36 ],
[ "Peter", 18 ],
[ "Lauren", 31 ],

您应该能够通过合并map语句中的值来进行更正。

替换...

let firstname = res.map(res => res.firstname);
let age = res.map(res => res.age);

有...

let data = res.map(res => [res.firstname, res.age]);

然后将数据添加到图表对象中...

this.charts.push({
  title: 'Customer Demographics',
  type: 'Bar',
  columnNames: ['Customer', 'Age'],
  roles: [],
  data: data,  // <-- add data here
  options: {
    chart: {
      title: 'Customer Demographics',
      subtitle: 'Sales, Expenses, and Profit: 2014-2017'
    },
    bars: 'vertical' // Required for Material Bar Charts.
  }