简体   繁体   English

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

[英]How implement Chart.js in Angular 2?

I am using the latest version of Angular 2, V4.0.0 and I want to use graphs from the Chart.js library in my project without many complications.我正在使用最新版本的 Angular 2,V4.0.0,并且我想在我的项目中使用来自 Chart.js 库的图形,而不会出现很多复杂情况。

How can I implement Chart.js in my angular project that does not give me problems in the final production?如何在我的 angular 项目中实现 Chart.js 而不会在最终生产中给我带来问题?

You can implement Chart.js in a simple way with the following instructions:您可以使用以下说明以简单的方式实现 Chart.js:

1. Create a new project with angular-cli, skip if you already have one created 1. 用angular-cli新建一个项目,已经创建的可以跳过

ng new example-chartjs

2. Install Chart.js in your project 2. 在你的项目中安装 Chart.js

npm install chart.js --save

3. Import Chart into its component 3. 将 Chart 导入到其组件中

import Chart from 'chart.js';

4. Use Chart in your view and component 4. 在你的视图和组件中使用 Chart

In your view:在您看来:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:在您的组件中:

ngOnInit() {

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

}

The component should look similar to the following该组件应类似于以下内容

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, {....});

  }

}

Another alternative to use is to include the library from the file ".angular-cli.json"另一种使用方法是包含文件“.angular-cli.json”中的库

1. Include in the scripts the library 1. 在脚本中包含库

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]

2. Declare a variable of type "any" in the controller 2.在控制器中声明一个“any”类型的变量

declare var Chart:any;

3. Use Chart in your view and component 3. 在你的视图和组件中使用 Chart

In your view:在您看来:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:在您的组件中:

ngOnInit() {

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

}

The component should look similar to the following该组件应类似于以下内容

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, {....});

  }

}

First第一的
npm install chart.js --save

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

Third - import Chart into component this way第三- 以这种方式将 Chart 导入到组件中
import * as Chart from 'chart.js';

I've implemented the Chart.js on Angular at this way(first you'll need to install it using npm install chart.js --save ):我已经通过这种方式在 Angular 上实现了 Chart.js(首先你需要使用npm install chart.js --save安装它):

The folder structure of my project我的项目的文件夹结构

src/
  assets/
  app/
    charjs/
    services/

First I've created a service called report.service.ts :首先,我创建了一个名为report.service.ts的服务:

src/app/services/report.service.ts src/app/services/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());
  }
}

This service it's created based on Angular tutorial showing how to get an external file(or link) and retrieve Json data.该服务是基于 Angular教程创建的,该教程展示了如何获取外部文件(或链接)并检索 Json 数据。

This is important to collect the data from external source(if you must)这对于从外部来源收集数据很重要(如果必须的话)

The difference between a service and a component, It's you need to to insert this service as a provider on the app.module.ts :服务和组件的区别在于,你需要在 app.module.ts 上插入这个服务作为提供者:

src/app/app.module.ts src/app/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 { }

After that I've created the component chartjs.component.js , and used AfterViewInit instead of OnInit.之后,我创建了组件 chartjs.component.js ,并使用 AfterViewInit 而不是 OnInit。 I've used this approach because our service retrieves the data in asynchronous and, because of that, the data can be returned before the view has been initiated.我使用这种方法是因为我们的服务以异步方式检索数据,因此,可以在启动视图之前返回数据。

src/app/chartjs/chartjs.component.ts src/app/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
      });

    });
  }

}

A few comments about this file;关于这个文件的一些评论;

. . After imported the service, I've used subscribe,to allow charjs library to get the data and push it on new Chart .导入服务后,我使用 subscribe 来允许 charjs 库获取数据并将其推送到new Chart ChartOptions its just a variable to change the chart view the way you want, I've used to create a bubble chart. ChartOptions 它只是一个变量,可以按照您想要的方式更改图表视图,我曾经创建过气泡图。 . . You can define if it's responsive or not.您可以定义它是否响应。

After you've done that, you'll need to set your html:完成后,您需要设置 html:

src/app/chartjs/chartjs.component.html src/app/chartjs/chartjs.component.html

<div style="height: 600px;width: 600px">
  <canvas #graphcanvas></canvas>
</div>

I hope that helps someone who couldn't implement on the other ways.我希望能帮助那些无法以其他方式实施的人。

I believe, on Angular, chartjs will work like below, because context is available afterViewInit() not onInit()我相信,在 Angular 上,chartjs 的工作方式如下所示,因为上下文在 ViewInit() 之后可用,而不是 onInit()

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

    @Component({
        selector: 'app-statistics',
        templateUrl: './statistics.component.html',
        styleUrls: ['./statistics.component.css']
    })
    export class StatisticsComponent implements AfterViewInit{
        @ViewChild('myChart') Chart: ElementRef;
        constructor() { 

        }

        ngAfterViewInit() {
            var ctx = this.Chart.nativeElement.getContext('2d')
            var myChart = new Chart(ctx,{...})
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM