javascript - 如何在 Angular 4 上使用带有 ChartJS 的插件

标签 javascript angular typescript npm chart.js

我正在尝试使用 PieceLabel 插件来显示图形内的标签,但它不起作用。图形显示正常,这是我的代码:

TS

import * as Chart from 'chart.js'
import * as ChartPiece from 'chart.piecelabel.js'

ngAfterViewInit() {
  this.canvas2 = document.getElementById('myChartPie');
  this.ctx2 = this.canvas2.getContext('2d');
  let myChartPie = new Chart(this.ctx2, {
    type: 'pie',
    data: {
        labels: ["one", "two", "three", "four"],
        datasets: [{
            label: '# of Score',
            data: [11,21,31,41],
            backgroundColor: [
                'red',
                'blue',
                'orange',
                'green'
            ]
        }]
    },
    options: {
            responsive: false,
      display:true,
      pieceLabel: {
    mode: 'value'
  }
    }
  });
}

我使用 npm install --save 安装了 Chart.js 和 Chart.piecelabel.js。我试图将它添加到 .angular-cli.json 文件中,但它似乎没有任何效果:

"scripts": [
        "../node_modules/chart.piecelabel.js/build/Chart.PieceLabel.min.js"
      ]

HTML

<canvas id="myChartPie" width="650px"></canvas>

看起来我的 PieceLabel.min.js 没有被调用/识别,我不确定为什么

最佳答案

这是因为,Chart.PieceLabel.js 插件没有任何导出成员(命名默认)。它只是将自己注册到 Chart.js 插件服务中。

因此,您的import 语句应该是:

import 'chart.piecelabel.js';

代替:

import * as ChartPiece from 'chart.piecelabel.js'

旁注: 您不需要在 angular-cli.json 中包含此插件脚本

关于javascript - 如何在 Angular 4 上使用带有 ChartJS 的插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414898/

相关文章:

javascript - 在 jsviews 中绑定(bind)到表单的正确语法(提交 26)

angular - 类型具有私有(private)属性模拟服务单元测试 Angular 7 的单独声明

typescript - 'declare' 在 'export declare class Actions' 中做什么?

javascript - 带有两个参数的“数据”回调不会将 buffer.toString() 打印为字符串

javascript - 在 JavaScript 中禁用 Opera 功能键

angular - 如何在 Storybook 中使用相对 Angular 分量?

angular - NullInjectorError : No provider for InjectionToken MatDialogData

angular - 在 app-routing.module.ts 中添加了新路由 - ngxAdmin 不起作用

node.js - Nest 无法解析 AuthGuard(Guard 装饰器)的依赖关系

javascript - 循环引用内存泄漏?