Angular集成amCharts5雷达图表时遇Cannot read properties of undefined(reading 'root')错误
Angular 中 amCharts5 雷达图 Bullet 报错排查
我在Angular环境里参考amCharts5雷达图表示例实现雷达图表时,添加bullet的代码段出现错误:ERROR TypeError: Cannot read properties of undefined (reading 'root')。测试发现,在bubbleSeries.bullets.push()代码之前能正常获取root实例,但回调函数内部访问this.root时显示为undefined。
报错代码段
// 添加Bullet let circleTemplate: am5.Template<am5.Circle> = am5.Template.new({}); bubbleSeries.bullets.push(function () { console.log("Root: ", this.root); let graphics = am5.Circle.new(this.root, { fill: distanceSeries.get("fill"), tooltipText: "{title}: {value} km" }, circleTemplate); return am5.Bullet.new(this.root, { sprite: graphics }); });
模板代码(radar-chart.component.html)
<div id="radarChart" style="width: 100%; height: 100%;"></div>
组件逻辑代码(radar-chart.component.ts)
完整代码包含骑行数据定义、初始化am5.Root、数据预处理、创建雷达图表及轴范围等逻辑。
问题原因及解决办法
问题出在普通函数的this指向:传递给bullets.push()的普通函数,内部this不会指向组件上下文,而是由调用它的环境决定,导致this.root为undefined。
有两种直接解决方式:
- 使用箭头函数绑定上下文
箭头函数会继承外部作用域的this,替换后即可正常访问组件的root实例:
// 添加Bullet let circleTemplate: am5.Template<am5.Circle> = am5.Template.new({}); bubbleSeries.bullets.push(() => { console.log("Root: ", this.root); let graphics = am5.Circle.new(this.root, { fill: distanceSeries.get("fill"), tooltipText: "{title}: {value} km" }, circleTemplate); return am5.Bullet.new(this.root, { sprite: graphics }); });
- 提前保存外部上下文到变量
如果必须使用普通函数,可以在外部先把组件的this存为变量,在回调中使用该变量访问root:
// 添加Bullet let circleTemplate: am5.Template<am5.Circle> = am5.Template.new({}); const self = this; // 保存组件上下文 bubbleSeries.bullets.push(function () { console.log("Root: ", self.root); let graphics = am5.Circle.new(self.root, { fill: distanceSeries.get("fill"), tooltipText: "{title}: {value} km" }, circleTemplate); return am5.Bullet.new(self.root, { sprite: graphics }); });
额外确认:组件中需确保已正确初始化this.root,比如:
this.root = am5.Root.new("radarChart");
内容的提问来源于stack exchange,提问作者Amal Thomas
相关产品推荐
相关产品推荐

