我正在开展Angular 4项目,我想使用ng2-charts
。
我按照https://valor-software.com/ng2-charts/上的说明操作,但是他们的说明不清楚或缺乏有关如何正确安装包的详细信息,例如它说:
重要说明:在应用程序中嵌入Chart.js是强制性的!
<script src="node_modules/chart.js/src/chart.js"></script>
我将此<script>
元素放在我的index.html
文件中,但它没有工作,因为我从ng serve
网络服务器命令中收到了404错误。
最终我找到了这个页面:https://alligator.io/angular/chartjs-ng2-charts/,其中解释说我实际上需要在Chart.min.js
文件的.angular-cli.json
数组中列出scripts: []
,phew!
我现在已经在Angular项目中使用了图表,但是我想使用TypeScript打字文件,因此我可以在Angular组件.ts
源中使用强类型数据绑定属性。
我运行了npm install @types/chartjs --save
- 这是这个库:https://www.npmjs.com/package/@types/chartjs,它提供了interface ChartDataSet
,interface ChartSettings
的定义,等等。
我的Component
看起来像这样:
@Component( { ... } )
export class FooComponent {
public chartData: Partial<ChartDataSet>[] = [
{ label: "Foo", data: [ 1, 2, 3, 4, 5 ] },
{ label: 'Bar', data: [ 5, 4, 3, 2, 1 ] }
];
public chartOptions: Partial<ChartSettings> = {
responsive: true
};
}
当我运行ng serve
时,我收到了这个编译错误:
C中的错误:/git/project/appmodule/foo.component.ts(32,33):找不到名称&#39; ChartDataSet&#39;。 C中的错误:/git/project/appmodule/foo.component.ts(37,33):找不到名称&#39; ChartSettings&#39;。
经过一些研究和实验,我手动将打字文件添加到我的src/tsconfig.app.json
文件中:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
],
"files": [
"../node_modules/@types/chartjs/index.d.ts"
]
}
我不喜欢这样 - 感觉我做错了什么,但确实有效,ng serve
成功构建项目。
但是,现在Visual Studio 2017(带有TypeScript 2.5.2)在我的foo.component.ts
文件中抱怨:
(TS) Cannot find name 'ChartDataSet'.
(TS) Cannot find name 'ChartSettings'.
我以为我通过将此行添加到foo.component.ts
的顶部来解决此问题:
/// <reference path="../../../node_modules/@types/chartjs/index.d.ts" />
但这令人惊讶地没有效果。
我也试过了其中的每一个:
import * as c from '@types/chartjs';
import * as c from '@types/chartjs/index';
import * as c from '@types/chartjs/index.d.ts';
在所有情况下,TypeScript都抱怨index
不是模块。
我在Visual Studio中看到,TypeScript使用tsconfig.json
而不是tsconfig.app.json
,因此我添加了&#34; index.d.ts entry to
tsconfig.json`(如然而,当我这样做时,它完全破坏了Visual Studio中的TypeScript,并且我有很多错误消息,如
(TS) Cannot find module '@rxjs/Observable'.
(TS) Cannot find module '@angular/core'.
(TS) Cannot find name 'module'.
etc...