ng2-charts - рабочий пример Angular 4

Я пытаюсь использовать ng2-диаграммы с Angular 4.0, и я хотел бы получить то же самое, что и здесь, с помощью chart.js:

    ...
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
    ...

    <canvas id="myChart" width="400" height="400"></canvas>
    <script>
        var ctx = document.getElementById("myChart").getContext('2d');
        var chart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'horizontalBar',

            // The data for our dataset
            data: {
                labels: ["example1","example2","example3","example4","example5","example6","example7"],
                datasets: [{
                    label: "My First dataset",
                    backgroundColor: 'rgb(255, 99, 132)',
                    borderColor: 'rgb(255, 99, 132)',
                    data: [0, 10, 5, 2, 20, 30, 45]
                },{
                    label: "My second dataset",
                    backgroundColor: 'rgb(2, 99, 132)',
                    borderColor: 'rgb(255, 99, 132)',
                    data: [3, 10, 5, 2, 20, 30, 45]
                }]
            },

            // Configuration options go here
            options: {
                scales: {
                    xAxes: [{
                        stacked: true
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                }
            }
        });
    </script>

Что я сделал, это

npm install ng2-charts --save
npm install chart.js --save

и я добавил

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

в src / index.html

а также

import { ChartsModule } from 'ng2-charts';

imports: [
   ChartsModule
]

в src / app / app.module.ts

Можете ли вы показать мне рабочий пример src / index.html, src / app / app.component.html и app / component.ts для него? Потому что у меня с этим проблемы, как в примере

GET 
http://localhost:4200/node_modules/chart.js/src/chart.js [HTTP/1.1 404 Not Found 8 ms]
ERROR Error: "undefined" is not a chart type.

даже если я изменю местоположение chart.js.

src / index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Chart</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

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

</head>

<body>
  <app-root>Loading...</app-root>
</body>
</html>

src / app / app.component.html

<h1>
  {{title}}
</h1>

    <div style="display: block">
      <canvas baseChart
              [data]="chartData"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
    </div>
    <button (click)="randomize()">Update</button>

src / app / app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  public chartData: Array<any> = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
  ];

}

person EA_    schedule 14.06.2017    source источник
comment
Попробуйте добавить chartType="horizontalBar" в <canvas baseChart   -  person yurzui    schedule 14.06.2017
comment
Теперь я кое-что вижу, а не белую страницу, спасибо! Но у меня все еще есть проблема с GET localhost: 4200 / node_modules / chart.js / dist / Chart.bundle.min.js [HTTP / 1.1 404: не найдено, 1 мс]   -  person EA_    schedule 14.06.2017
comment
Если у вас chart.js установлена ​​как зависимость, вы можете получить пакет по URL-адресу, который вам дал @EA_. В противном случае с node_modules/ng2-chart/node_modules/chart.js/dist/Chart.bundle.min.js   -  person Mathias Rodriguez    schedule 14.06.2017


Ответы (3)


Измените свой chart.js на

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

TS-код модуля приложения

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

// In your App's module:
imports: [
   ChartsModule
]

Обновить, удалите тег скрипта в index.html и добавьте

проверьте массив angular-cli.json и scripts, затем добавьте в него:

"../node_modules/chart.js/dist/Chart.bundle.min.js"

person CharanRoot    schedule 14.06.2017
comment
ПОЛУЧИТЕ localhost: 4200 / node_modules / chart.js / dist / Chart .bundle.min.js [HTTP / 1.1 404 не найдено, 1 мс] ОШИБКА Ошибка: undefined не является типом диаграммы. - person EA_; 14.06.2017
comment
вам не нужно включать файл js через тег скрипта. Достаточно включения в app.module.ts. import { ChartsModule } from 'ng2-charts'; - person Shaheen K; 25.09.2017
comment
как я могу добавить этот пакет в angular-quickstart, он показывает проблему с патчем в файле systemJs - person Muhammad Arslan; 20.10.2017
comment
Я согласен с Шахином. может ответ старше. используя cli 1.4.3 и ng2-charts 1.6.0, я установил ng2-charts через npm и импортировал модуль charts в свой модуль приложения import { ChartsModule } from 'ng2-charts'; imports: [ BrowserModule, FormsModule, HttpClientModule, ChartsModule ], и я смог получить диаграмму в моем компоненте без добавления скриптов в .angular-cli. json. Я действительно получаю какую-то ошибку в консоли, когда добавляю скрипт в .angular-cli.json. - person andrewramka; 31.12.2017

Помимо добавления файла chart.js в .angular-cli.json, вам не хватает только chartType, переданного в качестве входных для baseChart.

<canvas baseChart
        [chartType]="'horizontalBar'"
        [data]="chartData"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)"></canvas>
person Mathias Rodriguez    schedule 14.06.2017

импортировать {ChartsModule} из 'ng2-charts / ng2-charts';

// В модуле вашего приложения: import: [ChartsModule]

person arpit    schedule 30.10.2018