Angular项目使用google-charts出现google is not defined错误如何解决
问题原因
你在组件类属性初始化阶段直接实例化google.visualization.NumberFormat,此时Google Charts的第三方脚本还未加载完成,google全局对象尚未挂载到window上,因此抛出引用错误。
解决方法
通过GoogleChartsService的ready事件监听脚本加载状态,等脚本加载完成后再初始化格式化器:
- 首先在组件中导入并注入
GoogleChartsService - 将
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
相关产品推荐
相关产品推荐

