In this tutorial, we are going to learn how to integrate dynamic chart from database to ionic application, we are going to use Chart.js library to display our database information in chart and graph format.
First, let’s list what we need to do to achieve our task of the day.
- Create an ionic app called chartApp
- Install Chart.js library
- Setup chart and graph template in home.html page
- Create chart and graph in home.ts page
- Test our app
- Create table in our database
- Update home.ts to fetch data from database
- Create a php file to fetch data from database.
- Test our app
Ugh!! That’s quiet some work to do, let get started.
Are you READY?
- Create an ionic app called chartApp
Open you command Line Interface(CLI) and issue the following command
[cc] ionic start chartApp blank [/cc]
2. Install Chart.js library
Change directory to chartApp and install Chart.js with the following command as shown below
[cc] npm install chart.js –save [/cc]
3. Setup chart and graph template in home.html page
Open home.html page and update the content between <ion-content> </ion-content> tag as shown below
[cc]
Bar Chart
Doughnut Chart
Line Chart
[/cc]
4. Create chart and graph in home.ts page
Open home.ts and update content with the code below
[cc]
import { Component, ViewChild } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { Chart } from ‘chart.js’;
@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
@ViewChild(‘barCanvas’) barCanvas;
@ViewChild(‘doughnutCanvas’) doughnutCanvas;
@ViewChild(‘lineCanvas’) lineCanvas;
barChart: any;
doughnutChart: any;
lineChart: any;
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: ‘bar’,
data: {
labels: [“Apple”, “Mango”, “Cherries”, “Orange”,
datasets: [{
label: ‘# of Votes’,
data: [15, 19, 5, 10],
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’
],
borderColor: [
‘rgba(255,99,132,1)’,
‘rgba(54, 162, 235, 1)’,
‘rgba(255, 206, 86, 1)’,
‘rgba(75, 192, 192, 1)’
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: ‘doughnut’,
data: {
labels: [“Apple”, “Mango”, “Cherries”, “Orange”],
datasets: [{
label: ‘# of Votes’,
data: [15, 19, 5, 10],
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’
],
hoverBackgroundColor: [
“#FF6384”,
“#36A2EB”,
“#FFCE56”,
“#FF6384”
]
}]
}
});
this.lineChart = new Chart(this.lineCanvas.nativeElement, {
type: ‘line’,
data: {
labels: [“Apple”, “Mango”, “Cherries”, “Orange”],
datasets: [
{
label: “My First dataset”,
fill: false,
lineTension: 0.1,
backgroundColor: “rgba(75,192,192,0.4)””,
borderColor: “rgba(75,192,192,1)”,
borderCapStyle: ‘butt’,
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: ‘miter’,
pointBorderColor: ‘rgba(75,192,192,1)”,
pointBackgroundColor: “#fff”,
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: “rgba(75,192,192,1)”,
pointHoverBorderColor: “rgba(220,220,220,1)”,
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [15, 19, 5, 10],
spanGaps: false,
}
]
}
});
}
}
[/cc]
5. Test your app
At this point we have hard coded the data into our codes, though that is not our mission, but it is always nice to check with hard coded data before fetching data from database, we can easily trace the problem in case something goes wrong.
Now, let’s test our app by issuing he following code
[cc] ionic serve –l [/cc]Do you have this?
6. Create table in our database
Now that our chart is set with hard coded data, let’s us create a table in our database and seed it with our fictitious data
Now, let head to our database and create a table called fruits with the following column and data type:
- id – int(11) – auto-incremental
- fruit – varchar(25)
- quantity – int(11)
as shown below
Now, let’s seed the table with the data below
id | fruit | quantity |
1 | Apple | 15 |
2 | Mango | 19 |
3 | Cherries | 5 |
4 | Orange | 10 |
7. Update home.ts to fetch data from database
Open home.ts, update the contents as shown below
[cc]
import { Component, ViewChild} from ‘@angular/core’;
import { NavController, AlertController } from ‘ionic-angular’;
import { LoadingController } from ‘ionic-angular’;
import {Http, Headers, RequestOptions} from ‘@angular/http’;
import { Chart } from ‘chart.js’;
import ‘rxjs/add/operator/map’;
@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
@ViewChild(‘barCanvas’) barCanvas;
@ViewChild(‘doughnutCanvas’) doughnutCanvas;
@ViewChild(‘lineCanvas’) lineCanvas;
barChart: any;
doughnutChart: any;
lineChart: any;
items:any;
var_x:any;
var_y:any;
constructor(public navCtrl: NavController, public loading: LoadingController,
public alertCtrl: AlertController, public http: Http) {
}
ionViewDidLoad() {
var headers = new Headers();
headers.append(“Accept”, ‘application/json’);
headers.append(‘Content-Type’, ‘application/json’ );
let options = new RequestOptions({ headers: headers });
let loader = this.loading.create({
content: ‘Processing please wait…’,
});
loader.present().then(() => {
this.http.post(‘http://ionicdon.com/mobile/fetch_fruits_info.php’,options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
this.items=res.server_response;
this.var_x = this.items.map(item => item.fruit);
this.var_y= this.items.map(item => item.quantity);
this.barChart = new Chart(this.barCanvas.nativeElement, {
type: ‘bar’,
data: {
labels: this.var_x,
datasets: [{
label: ‘# of Votes’,
data: this.var_y,
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’
],
borderColor: [
‘rgba(255,99,132,1)’,
‘rgba(54, 162, 235, 1)’,
‘rgba(255, 206, 86, 1)’,
‘rgba(75, 192, 192, 1)’
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: ‘doughnut’,
data: {
labels: this.var_x,
datasets: [{
label: ‘# of Votes’,
data: this.var_y,
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’
],
hoverBackgroundColor: [
“#FF6384”,
“#36A2EB”,
“#FFCE56”,
“#FF6384”
]
}]
}
});
this.lineChart = new Chart(this.lineCanvas.nativeElement, {
type: ‘line’,
data: {
labels: this.var_x,
datasets: [
{
label: “My First dataset”,
fill: false,
lineTension: 0.1,
backgroundColor: “rgba(75,192,192,0.4)”,
borderColor: “rgba(75,192,192,1)”,
borderCapStyle: ‘butt’,
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: ‘miter’,
pointBorderColor: “rgba(75,192,192,1)”,
pointBackgroundColor: “#fff”,
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: “rgba(75,192,192,1)”,
pointHoverBorderColor: “rgba(220,220,220,1)”,
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: this.var_y,
spanGaps: false,
}
]
}
});
});
});
}
}
[/cc]
8. Create a php file to fetch data from database.
[cc]
$row[0],
“fruit”=>$row[1],
“quantity”=>$row[2] ));
}
echo json_encode(array(“server_response”=> $response));
mysqli_close($con)
?>
[/cc]Save this file as fetch_fruits_info.php
9. Test our app
Now that everything is set, let’s test to see our final output