Professional Documents
Culture Documents
1 : install modules
npm i chartjs-plugin-datalabels@0.7.0
npm i ng2-charts@2.3.0
npm i chart.js@2.9.3
2 : app .module.ts
import { ChartsModule } from 'ng2-charts';
imports: [
ChartsModule
]
mkdir model
cree fichier chart.ts
export class Chart {
teamOne: string;
teamTwo: string;
scoreOne: number;
scoreTwo: number;
}
example :
3 :chart.html
<div class="top-charts">
<div class="chart">
<canvas baseChart [data]="pieChartData"
[labels]="pieChartLabels" [chartType]="pieChartType"
[options]="pieChartOptions" [plugins]="pieChartPlugins"
[colors]="pieChartColors" [legend]="pieChartLegend">
</canvas>
</div>
</div>
4:chart.ts
import { Component, OnInit } from '@angular/core';
import { ChartType, ChartOptions } from 'chart.js';
import { Label } from 'ng2-charts';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';
import { MatchService } from 'src/app/service/match.service';
import { Chart } from '../../models/Chart';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: [ './chart.component.css' ]
})
export class ChartComponent implements OnInit {
ngOnInit() {
this.getChartData();
}
getChartData() {
this.api.getChart().subscribe(
(res: any) => {
console.log('here res chart', res);
this.chartData = res.matches;
this.pieChartLabels = [];
this.pieChartData = [];
this.pieChartColors = [];
const backgrounds = [];
this.chartData.forEach((ch, idx) => {
this.pieChartLabels.push(ch.teamOne);
this.pieChartData.push(ch.scoreOne);
backgrounds.push(`rgba(${0 + idx * 10}, ${255 - idx
* 20}, ${0 + idx * 10}, 0.3)`);
});
this.pieChartColors = [
{
backgroundColor: backgrounds
}
];
},
(err) => {
console.log(err);
}
);
}
}
5 : Service.ts :
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { Chart } from './../models/Chart';
@Injectable({
providedIn: 'root'
})
export class MatchService {
matchUrl = 'http://localhost:3000/matches';
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
constructor(private httpClient: HttpClient) {}
getChart(): Observable<Chart> {
const url = `${this.matchUrl}`;
return this.httpClient
.get<Chart>(url)
.pipe(tap((_) => console.log(`fetched chart data`)),
catchError(this.handleError<Chart>(`getChart data`)));
}
}
6 : app.js
// traitement logique de matches
app.get('/matches', (req, res) => {
console.log('here in get all matches');
Match.find((err, docs) => {
if (err) {
console.log('error widh DB');
} else {
res.status(200).json({
matches: docs
});
}
});
});