echarts图渲染后,再次更新数据发现无法刷新图表。
解决办法就是手动刷新,重新set一下option:
废话不多少,直接上方法:
首先要拿到图表所在的dom,试了很多方法,发现下面这个可以:
<div echarts (chartInit)="chartInit($event)" [options]="options" style="height: 200px;width: 90%;"></div>
chartInit方法的目的是将echart所在的dom传出来。
然后,在ts中使用:
chartInit(event) {
this.echartsIntance = event;
console.log(this.echartsIntance);
}
打印结果如下:

点开object,发现拿到的是对的,确实有setOption方法:

this.echartsIntance.setOption(this.options);//使用拿到的dom重新set option。
其他方法也试过,比如通过@ViewChild获取子组件,但是好像不太行:
<div #myChart echarts [options]="options" style="height: 200px;width: 90%;"></div>
import { Component, OnInit, Input,ViewChild,ElementRef } from '@angular/core';
import {HomeService} from '../../../home.service';
import { inputSelection } from 'ng-zorro-iop';
@Component({
selector: 'server-overview',
templateUrl: './server-overview.component.html',
styleUrls: ['./server-overview.component.less']
})
export class ServerOverviewComponent implements OnInit {
@Input() groupName:String;
@ViewChild('myChart',{static:false}) chart:any;
constructor(private homeService: HomeService) { }
isShowExpand = false;
isLoading = false;
hostList = [];
piedata = [
{ value: 0,name: '正常'},
{ value: 0,name: '异常'}
]
options = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
x: 'right',
y: 'center',
orient: 'vertical',
//图例位置(在内容左边还是右边)
align: 'left',
formatter: (name) => {
let arr = [];
this.piedata.forEach(element => {
if (element.name == name) {
arr = [name + ' ' + element.value]
}
});
return arr;
}
},
calculable: true,
series: [
{
labelLine: {show: false},
label: {show:false},
name: '主机活跃情况',
type: 'pie',
radius: ['45%', '70%'],
data: this.piedata,
}
]
};
ngOnInit() {
this.getHostList(this.groupName);
}
getHostList(groupName){
let normalCount = 0;
let unnormalCount = 0;
let body = {group:groupName}
this.homeService.hostList(body).subscribe(res => {
if(res != undefined && res.code == "200"){
this.hostList = res.result;
this.hostList.forEach(host => {
if(host.status == "normal"){
normalCount ++;
}else{
unnormalCount ++;
}
this.piedata.find(ele => ele.name == "正常").value = normalCount;
this.piedata.find(ele => ele.name == "异常").value = unnormalCount;
this.chart.chartInstance.setOption(this.options);
// this.echartsIntance.setOption(this.options);
})
}
})
}
}
这样拿不到echart的实例,打印出来显示只是普通的一个dom:

可能是我写的有问题吧,希望大佬帮忙指正哪里写错了,我还是想用@ViewChild这种方式的。
本文介绍了在Angular应用中遇到ECharts图表数据更新后无法自动刷新的问题,提供了一个通过手动调用`setOption`方法来刷新图表的解决方案。首先通过`chartInit`方法获取图表实例,然后在数据更新后使用该实例的`setOption`方法重新设置图表选项,从而实现图表的刷新。同时,尝试了使用`@ViewChild`获取图表实例但未能成功,可能是因为写法有误,期待社区中的专家提供帮助。
1430

被折叠的 条评论
为什么被折叠?



