2

我刚开始使用 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 以生成一些 .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

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

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' 
      }
    }

希望有一天它会帮助某人

4

4 回答 4

3

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

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

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

于 2017-01-08T16:12:08.600 回答
2

如果您使用 angular cli,请将其添加到 angular-cli.json 中的脚本部分

  "../node_modules/chart.js/dist/Chart.bundle.min.js"
于 2017-07-01T17:44:52.083 回答
0

在 system.config.js 中,我必须将 chart.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',
  }

}
于 2017-10-07T16:44:18.213 回答
0

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

于 2021-07-13T17:51:14.953 回答