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

Angular项目使用google-charts出现google is not defined错误如何解决

问题原因

你在组件类属性初始化阶段直接实例化google.visualization.NumberFormat,此时Google Charts的第三方脚本还未加载完成,google全局对象尚未挂载到window上,因此抛出引用错误。

解决方法

通过GoogleChartsService的ready事件监听脚本加载状态,等脚本加载完成后再初始化格式化器:

  1. 首先在组件中导入并注入GoogleChartsService
  2. 将myFormatters的初始化逻辑放到ready事件的回调中执行

修改后的component.ts代码如下:

import { Component } from '@angular/core';
import { GoogleChartsService } from '@angular/google-charts';

@Component({
  // 你的原有组件配置
})
export class OutputFrtbsaReportingComponent {
  type = 'AreaChart';
  dataArea = [];
  options = {
    isStacked: true,
    pointSize: 4,
    chartArea: { left: 40, top: '5%', width: '85%', height: '80%' },
    legend: { position: 'none' },
    height: 380,
    colors: ['rgb(0, 0, 128)', 'grey', 'orange'],
    vAxis: {format: 'short'}
  };
  // 先声明空数组,等脚本加载完成后再赋值
  myFormatters: any[] = [];

  constructor(private googleChartsService: GoogleChartsService) {
    // 监听Google Charts加载完成事件
    this.googleChartsService.ready.subscribe(() => {
      this.myFormatters = [
        {
          formatter: new google.visualization.NumberFormat({ 
            decimalSymbol: '.',
            groupingSymbol: ',' 
          }),
          colIndex: 1
        },
        {
          formatter: new google.visualization.NumberFormat({ 
            decimalSymbol: ',',
            groupingSymbol: '.' 
          }),
          colIndex: 5
        }
      ];
    });
  }
}
前置检查项
  • 确保已经在根模块/AppModule中正确导入了GoogleChartsModule,否则服务无法正常注入
  • 确认项目依赖中已经正确安装了@angular/google-charts包

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:39:04