You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中Google Charts绘制图表返回undefined值问题求助

问题分析与解决方案

核心问题1:this指向丢失

当你把this.drawColumnChart传给google.charts.setOnLoadCallback时,回调函数执行时的this不再指向组件实例,导致this.tableContent为undefined,自然无法读取region属性。

核心问题2:数组循环与DataTable构建错误

  1. 数组索引从0开始,循环条件用i <= datas.length会导致最后一次循环访问datas[datas.length],这是数组外的位置,值为undefined
  2. 每次循环都重新创建graphic对象,最终只会保留最后一条数据,无法生成完整的图表数据

修正后的代码

component.ts

declare var google: any;

@Component({selector, template...})
export class AppComponent implements OnInit {
    tableContent!: ProgressTableDatas[];

    constructor(private dropdownService: DropdownService) { }

    ngOnInit(): void {
        this.tableContent = this.dropdownService.getProgressTableDatas();

        // 用箭头函数绑定this,确保回调里的this指向组件实例
        google.charts.load('current', { packages: ['corechart'] });
        google.charts.setOnLoadCallback(() => this.drawColumnChart());
    }

    drawColumnChart() {
        // 构建完整的图表数据:先设置表头,再批量添加数据行
        const chartData = [['Region', 'Budget', 'Closed']];
        this.tableContent.forEach(item => {
            // 把字符串类型的数值转为数字,Google Charts需要数字类型渲染数值图表
            chartData.push([item.region, parseFloat(item.budget), parseFloat(item.closed)]);
        });

        const graphic = google.visualization.arrayToDataTable(chartData);
        const chart = new google.visualization.ColumnChart(document.getElementById('progressGraphic'));
        // 可根据需求添加图表配置
        const options = {
            title: '区域预算与完成数据',
            hAxis: { title: '区域' },
            vAxis: { title: '金额' }
        };
        chart.draw(graphic, options);
    }
}

额外说明

  • 原数据中的budget和closed是字符串类型,必须转为数字才能让Google Charts正确绘制数值类图表
  • 去掉了无意义的this.tableContent.map(data => data)操作,浅拷贝数组对当前逻辑没有帮助
  • 用forEach替代for循环,代码更简洁易读

内容的提问来源于stack exchange,提问作者Henrique Fernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:25:17