Angular HighCharts中JSON对象属性无法通过this访问求助
Angular Highcharts Tooltip Formatter中this属性访问问题解决
问题原因
在Angular + Highcharts场景下,tooltip的formatter函数中,控制台打印this是包含x/y等属性的Point对象,但直接用this.x触发运行时错误,核心原因有两个:
- TypeScript无法自动识别
this的类型,导致编译/运行时类型校验报错; - 如果误用箭头函数作为formatter,
this会绑定到Angular组件实例而非Highcharts的Point对象。
解决方法
1. 普通函数+类型断言(快速解决)
确保formatter是普通函数(不要用箭头函数),通过类型断言让TypeScript识别this的结构:
tooltip: { formatter: function() { const point = this as any; console.log(point.x); // 正常访问x属性 return `数据:${point.key},值:${point.y}`; } }
2. 自定义类型(规范写法)
如果需要类型提示,可以自定义匹配控制台输出的Point接口,再进行断言:
// 定义对应结构的Point类型 interface ChartPoint { x: any[]; y: number; color: string; colorIndex: number; key: string; } tooltip: { formatter: function() { const point = this as ChartPoint; console.log(point.x); // 带类型提示的属性访问 } }
3. 利用Highcharts官方类型
导入Highcharts的Point类型,直接指定this的类型,让TypeScript自动识别属性:
import * as Highcharts from 'highcharts'; tooltip: { // 明确指定this为Highcharts.Point类型 formatter: function(this: Highcharts.Point) { console.log(this.x); // 无类型报错,直接访问属性 return `X: ${this.x}, Y: ${this.y}`; } }
避坑提醒
绝对不要用箭头函数作为formatter,否则this会指向Angular组件实例,而非Highcharts的Point对象:
// 错误写法:箭头函数导致this指向组件实例 tooltip: { formatter: () => { console.log(this.x); // 此处this无x属性,必然报错 } }
内容的提问来源于stack exchange,提问作者Himanshu
相关产品推荐
相关产品推荐

