import { CosmosChartService, light, dark, zh, en } from './../common/chart.service'; import * as echarts from 'echarts'; import { Timer } from './../../utils/timer'; //注册 echarts 主题 import * as lightJson from '../../theme/chart/light'; import * as darkJson from '../../theme/chart/dark'; echarts.registerTheme('light', lightJson.light); echarts.registerTheme('dark', darkJson.dark); export class BaseChart { private chart: echarts.ECharts; private container: HTMLDivElement; private service: CosmosChartService; private timer: Timer; private resizeBindHandler: any; protected chartOption: any; constructor(service: CosmosChartService) { this.service = service; // 绑定 resize 函数 this.resizeBindHandler = this.resizeHandler.bind(this); // 监听语言变化 this.service.missionLangChart$.subscribe(lang => { this.init(); }); // 监听主题变化 this.service.missionThemeChart$.subscribe(theme => { if (this.chart) { this.chart.dispose(); } if (this.container) { if (theme == light) { this.chart = echarts.init(this.container, 'light'); } else { this.chart = echarts.init(this.container, 'dark'); } } this.init(); }); // 默认值 this.resizeEnable = true; } // 供外部引用的 echarts 实例 public get echarts(): echarts.ECharts { return this.chart; } // 设置 echarts 容器,此时会自动初始化 chart protected set chartContainer(container: HTMLDivElement) { if (container) { this.container = container; setTimeout(() => { if (this.service.themeService.currentTheme == light) { this.chart = echarts.init(this.container, 'light'); } else { this.chart = echarts.init(this.container, 'dark'); } this.init(); }, 300); } } private init() { if (this.chart && this.chartOption) { this.inputOption(); } } protected inputOption() { if (this.chart && this.chartOption) { this.chart.setOption(this.chartOption, true); this.onInitChart(); } } protected onInitChart() { console.log('onInitChart...'); } protected disposeChart() { this.resizeEnable = false; if (this.chart) { this.chart.dispose(); this.chart = null; } this.onDestroyChart(); } protected onDestroyChart() { console.log('onDisposeChart...'); } // 缩放窗口时自动缩放 protected set resizeEnable(resize: boolean) { if (resize) { this.timer = new Timer(); window.addEventListener('resize', this.resizeBindHandler, false) } else { this.timer = null; window.removeEventListener('resize', this.resizeBindHandler, false); } } protected resizeHandler() { // console.log('resizeHandler') this.timer.startTimeOut(0.5, () => { this.timer.stopTimeOut(); if (this.chart) { this.chart.resize(); } }, this); } }