Angular 项目中如何使用 ECharts

在有些使用 ECharts 库的 Angular 项目中,通常除了安装 npm 包之外,还会在 angular.json 中配置 “build.options.scripts”,将 “node_modules/echarts/dist/echarts.min.js”放入其中:

"projects": {
  "<project-name>": {
    "architect": {
      "build": {
        "options": {
          //other config
          "scripts": [
            "node_modules/echarts/dist/echarts.min.js"
          ]
        }
      }
    }
  }
}

然后在需要使用的 TypeScript 单元顶部声明:

declare var echarts: any;

这样的做法看起来“不太像” TypeScript 的操作方式~

其实在使用 Angular 和 ECharts 的较新版本(ngx-echarts(ver >= 2.x),ECharts (ver >= 3.x))时,有更好的方式在 Angular 项目中引入 ECharts:

1、安装 npm 包:

1 npm install echarts -S
2 npm install ngx-echarts -S
3 npm install @types/echarts -D

2、在 module (比如 app.module.ts)中引入模块:

1 import { NgxEchartsModule } from 'ngx-echarts';
2 @NgModule({
3   imports: [
4     ...,
5     NgxEchartsModule
6   ],
7 })
8 export class AppModule { }

3、使用 ECharts:

1 import * as echarts from "echarts";
2  
3 const echartsObject = echarts.init(document.getElementById("myChart"));

或者只导入必须的 API:

1 import { init as echartsInit } from "echarts";
2  
3 const echartsObject = echartsInit(document.getElementById("myChart"));

参考

https://xieziyu.github.io/ngx-echarts/#/home
https://xieziyu.github.io/ngx-echarts/api-doc/

猜你喜欢

转载自www.cnblogs.com/Jaffray/p/10676127.html