【发布时间】:2020-08-16 11:17:30
【问题描述】:
我有以下 component.ts
的代码export class HomeComponent implements OnInit {
Linecap = {};
dataArray=[];
constructor(private chartGetDataService: ChartGetDataService) {
}
ngOnInit(): void {
this.chartPlotting();
}
public testMethod(){
this.chartGetDataService.getLatestData1().subscribe( list=>{ this.dataArray=list.map(item=>{return item.payload.val()});} );
console.log(this.dataArray);
return this.dataArray;
}
public chartPlotting(){
this.Linecap= new Chart('canvas',
{
type: 'line',
data: { labels: [moment().toDate().getTime()], datasets: [{ label:'Flow',yAxisID: 'A',lineTension: 0, data: [] , borderColor: '#3cb371', fill: false ,borderWidth:2},
]
},
options: { responsive: true,animation: {duration: 0},hover: {animationDuration: 0},responsiveAnimationDuration: 0,
scales: { xAxes: [{ type: 'realtime',time: { parser: undefined} , display: true }],
yAxes: [{ id:'A', display: true, ticks: { beginAtZero: true, fontColor:'#f4af07', stepSize: 10, max: 100}},
]
},
plugins: { streaming: {
duration: 60000,
refresh: 2000,
delay: 3000,
pause: false,
ttl: undefined,
frameRate: 2,
onRefresh: function(Linecap) {
console.log(this.testMethod())
console.log(this.dataArray)
Linecap.data.datasets[0].data.push({x: Date.now(), y: this.dataArray[2] });
Linecap.update({ preservation: true });
}
}
},
}
})
}
我在这段代码中遇到了 2 个问题。
- 我在 testMethod() 中的第一个 console.log 返回所需的值,这意味着方法工作正常并且值存储在 dataArray 但是当我尝试读取 onRefresh
Linecap.data.datasets[0].data.push({x: Date.now(), y: this.dataArray[2] });函数中的 dataArray 它给了我错误 ERROR TypeError: Cannot read property 'dataArray' of undefined - 如果我在像
var ws=this.testMethod()这样的 onRefresh 函数中调用 testMethod,它会给我错误 ERROR TypeError: Cannot read property 'testMethod' of undefined。后续调用console.log(this.testMethod())也会抛出同样的错误
我做错了什么?我找不到它。如何解决此代码的未定义错误。如果我在 onRefresh 函数之外调用 testMethod,它可以完美运行,但它返回空 dataArray。
【问题讨论】:
标签: javascript angular typescript chart.js chartjs-2.6.0