如何在Angular 2中实现Chart.js?

Vip*_*opy 5 html javascript typescript chart.js angular

我使用的是最新版本的Angular 2,V4.0.0,我想在我的项目中使用Chart.js库中的图形而没有太多复杂情况.

如何在我的角度项目中实现Chart.js,它不会在最终生产中给我带来问题?

Vip*_*opy 18

您可以使用以下说明以简单的方式实现Chart.js:

1.使用angular-cli创建一个新项目,如果已​​经创建了一个项目则跳过

ng new example-chartjs
Run Code Online (Sandbox Code Playgroud)

2.在项目中安装Chart.js.

npm install chart.js --save
Run Code Online (Sandbox Code Playgroud)

3.将图表导入其组件

import Chart from 'chart.js';
Run Code Online (Sandbox Code Playgroud)

4.在视图和组件中使用图表

在你看来:

<canvas id="myChart" width="400" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}
Run Code Online (Sandbox Code Playgroud)

该组件应类似于以下内容

import { Component, OnInit } from '@angular/core';
import Chart from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
Run Code Online (Sandbox Code Playgroud)

另一种使用方法是从文件".angular-cli.json"中包含库.

1.在脚本中包含库

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]
Run Code Online (Sandbox Code Playgroud)

2.在控制器中声明一个"any"类型的变量

declare var Chart:any;
Run Code Online (Sandbox Code Playgroud)

3.在视图和组件中使用图表

在你看来:

<canvas id="myChart" width="400" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}
Run Code Online (Sandbox Code Playgroud)

该组件应类似于以下内容

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

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
Run Code Online (Sandbox Code Playgroud)


小智 7

第一
npm install chart.js --save

第二
npm install @types/chart.js --save

第三 - 以这种方式将图表导入组件
import * as Chart from 'chart.js';


Luc*_*ira 5

我已经以这种方式在Angular上实现了Chart.js(首先你需要使用它来安装它npm install chart.js --save):

我项目的文件夹结构

src/
  assets/
  app/
    charjs/
    services/
Run Code Online (Sandbox Code Playgroud)

首先,我创建了一个名为的服务report.service.ts:

SRC /应用程序/服务/ report.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ReportService {
  constructor(public http: Http) {
  }
  getReports() {
    return this.http.get('assets/report.json')
      .map(res => res.json());
  }
}
Run Code Online (Sandbox Code Playgroud)

它是基于Angular 教程创建的,它显示了如何获取外部文件(或链接)并检索Json数据.

这对于从外部源收集数据很重要(如果必须的话)

服务和组件之间的区别,您需要在app.module.ts上将此服务作为提供者插入:

SRC /应用程序/ app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpModule, JsonpModule } from '@angular/http';
import { ReportService } from './services/report.service';
import { ChartjsComponent } from './chartjs/chartjs.component';

@NgModule({
  declarations: [
    AppComponent,
    ChartjsComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [ReportService],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

之后我创建了组件chartjs.component.js,并使用AfterViewInit而不是OnInit.我使用这种方法是因为我们的服务以异步方式检索数据,因此,可能在视图启动之前提供数据.

SRC /应用/ chartjs/chartjs.component.ts

import { Component, AfterViewInit,ViewChild, ElementRef } from '@angular/core';
import Chart from 'chart.js';
import { Respon2se } from '@angular/http';
import 'rxjs/add/operator/map';
import { ReportService } from '../services/report.service';


@Component({
  selector: 'app-chartjs',
  templateUrl: './chartjs.component.html',
  styleUrls: ['./chartjs.component.css']
})
export class ChartjsComponent implements AfterViewInit {

  @ViewChild('graphcanvas') mycanvas:ElementRef;
  createData;
  chartOptions;

  constructor(public reportService: ReportService) {

  }

  ngAfterViewInit() {

    this.reportService.getReports().subscribe(reportsData => {
      this.createData = {
        labels: 'Scatter Dataset',
        datasets: [{
          label: "reportRetrieve",
          data: reportsData,

        }]
      };

      this.chartOptions = {
        legend: {
          display: false,
          position: 'top',
          labels: {
            boxWidth: 80,
            fontColor: 'black'
          }
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
              color: "black"
            },
            scaleLabel: {
              display: true,
              labelString: "Report Size",
              fontColor: "red"
            }

          }],
          yAxes: [{
            gridLines: {
              color: "black",
              display: false
            },
            scaleLabel: {
              display: true,
              labelString: "Chart Report",
              fontColor: "green"
            }
          }]
        },
        layout: {
          padding: {
            left: 0,
            right: 50,
            top: 50,
            bottom: 0
          }
        },
        maintainAspectRatio: false
      };

      let ctx = this.mycanvas.nativeElement.getContext('2d');

      new Chart(ctx, {
        type: 'bubble',
        data: this.createData,
        options: this.chartOptions,
        responsive: false
      });

    });
  }

}
Run Code Online (Sandbox Code Playgroud)

关于这个文件的一些评论;

.导入服务后,我使用了subscribe,允许charjs库获取数据并将其推送new Chart .ChartOptions它只是一个变量,可以按照你想要的方式更改图表视图,我习惯于创建一个气泡图..您可以定义它是否响应.

完成后,您需要设置您的html:

SRC /应用/ chartjs/chartjs.component.html

<div style="height: 600px;width: 600px">
  <canvas #graphcanvas></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

我希望能帮助那些无法以其他方式实施的人.