Angular2 & ng2-图表模块:

Angular2 & ng2-charts module :

我刚开始使用 angular2,并且完成了英雄之旅教程: https://angular.io/docs/ts/latest/tutorial/

我更进一步,做了一些自定义代码,一切都很好。

但是,当我尝试使用 ng2-chart 模块时,我无法让它工作: http://valor-software.com/ng2-charts/

我做到了

npm install ng2-charts --save

还有这个

npm install chart.js --save

但是,当将 js 导入我的索引文件时,这不起作用:

<script src="node_modules/chart.js/src/chart.js"></script>

所以我不得不用这个来修复它:

<script src="node_modules/chart.js/dist/Chart.bundle.min.js"></script>

接下来是让我头疼的部分:

//app.module.ts    
import {ChartsModule} from 'ng2-charts/ng2-charts'; 
...

imports: [ 
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    ChartsModule,
  ],
....

我总是

GET localhost:3000/ng2-charts/ng2-charts 404 (Not Found)
Error: (SystemJS) XHR error (404 Not Found) loading localhost:3000/ng2-charts/ng2-charts
    Error: XHR error (404 Not Found) loading localhost:3000/ng2-charts/ng2-charts
        at XMLHttpRequest.wrapFn [as _onreadystatecha

很高兴知道如果我导入

import {ChartsModule} from 'node_modules/ng2-charts/ng2-charts'

我的服务器哭了

app/app.module.ts(17,31): error TS2307: Cannot find module 'node_modules/ng2-charts/ng2-charts'.

要记住的事情:我是 js 和 angular2 世界的新手,我想我仍然不太了解这里的工作原理。 我看到有些人和我有同样的问题,但我不明白答案/我不能使用它们,因为我的应用程序架构是英雄之旅中的架构,我不熟悉 angular2 来改变它现在。

我怀疑有3个问题: 我应该将 "ng2-charts" 绑定到 "node_modules/ng2-charts" / 路径本身是错误的 / ng2-charts 应该是 "compiled" 来生成一些 .js 文件,但它不是。

一些有用的信息:

  $ npm -v
    3.10.9
    $ tsc -v
    message TS6029: Version 1.5.3
    $ ng -v
    angular-cli: 1.0.0-beta.24
    node: 6.9.2
    os: win32 x64
    @angular/common: 2.4.2
    @angular/compiler: 2.4.2
    @angular/core: 2.4.2
    @angular/forms: 2.4.2
    @angular/http: 2.4.2
    @angular/platform-browser: 2.4.2
    @angular/platform-browser-dynamic: 2.4.2
    @angular/router: 3.4.2

(如果有人能给我一个 link 来了解如何将英雄之旅架构打包到生产中,那就太好了) 谢谢大家

EDIT

通过将此添加到我的 systemjs.config.js 文件解决了问题:

map: {
      'ng2-charts': 'node_modules/ng2-charts',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      "node_modules/ng2-charts": {
        defaultExtension: 'js' 
      }
    }

希望有一天能对某人有所帮助

只需将您的 chart.js 导入更改为 index.html 文件中的 cdn link,如下所示,并按照文档保留其他所有内容。

 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.min.js"></script>

对我有用。希望这会有所帮助:)

如果您使用 angular cli

,请将此添加到 angular-cli.json 中的脚本部分
  "../node_modules/chart.js/dist/Chart.bundle.min.js"

在 system.config.js 中,我必须将 charts.js 添加到地图和包中以使其成为 运行。

map: {
  'ng2-charts': 'npm:ng2-charts',
  'chart.js': 'npm:chart.js/dist/Chart.min.js',
},
packages: {
  'ng2-charts': {
    main: './index.js',
    defaultExtension: 'js'
  },
  'chart.js': {
    defaultExtension: 'js',
  }

}

希望这对某人有所帮助,对我个人而言,它是导入 import { ChartsModule } from 'ng2-charts'; 而不是 import { ChartsModule } from ng2-charts/ng2-charts;