0

I'm building an ionic app to display dashboard (pie chart) by retrieving the data from URL/HTTP request. Here is my code in .ts file calling data from the url and I managed to display this in a table form using e.g. {{ items.data }} in .html file:

public items : Array<any> = [];

ionViewWillEnter() : void{
      this.load();
   }

 load() : void{
          this.http.get('http://localhost/test/retrieve-data.php')
          .subscribe((data : any) =>{
             console.dir(data);
             this.items = data;
          },
          (error : any) =>{
             console.dir(error);
          });
       }

My problem here is I want to retrieve data from ONE row and display it in pie chart. For example, this is that one row that I wanna fetch:

[{"id":9,"twitter_name":"Max Payne","positive_tweets":24,"negative_tweets":14,"total_tweets":38,"pos_percent":63,"neg_percent":37}]

I want to display a pie chart that shows values of pos_percent and neg_percent.

Here is what I've been doing and still stuck on calling the row data:

@ViewChild('pieChart') pieChart;

public pieChartEl : any;

createPieChart()
   {

      this.pieChartEl           = new Chart(this.pieChart.nativeElement,
      {
         type: 'pie',
         data: {
             labels: ["Positive","Negative"],
             datasets: [{
                 data                  : [],
                 duration              : 2000,
                 easing                : 'easeInQuart',
                 backgroundColor       : "rgba(54, 116, 152, 0.5)",
                 hoverBackgroundColor  : "rgba(160, 116, 152, 0.5)"
             }]
         },
         options : {
            maintainAspectRatio: false,
            layout: {
               padding: {
                  left     : 50,
                  right    : 0,
                  top      : 0,
                  bottom   : 0
               }
            },
            animation: {
               duration : 5000
            }
         }
      });



      this.chartLoadingEl = this.pieChartEl.generateLegend();
   }

ionViewDidLoad()
   {
      this.createPieChart();
   }

How do I fetch that data?

2 Answers 2

2

To draw PieChart with from HTTP request, Please follow my instruction below:

1- Make sure you install Angular 2 charts and Charts.js, simply type this command:

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

2- Register ChartsModule:

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ChartsModule } from 'ng2-charts';
import { Http, HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    HttpModule,
    BrowserModule,
    IonicModule.forRoot(MyApp),
    ChartsModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

3- Add Canvas tag to your html file like below:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>

  <div style="display: block">
    <canvas baseChart #baseChart="base-chart"
                [data]="doughnutChartData"
                [labels]="doughnutChartLabels"
                [chartType]="doughnutChartType"></canvas>
  </div>

</ion-content>

4: Get json data and draw to canvas:

Note: I load json from asset/datas.json via HTTP.

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http, Response} from '@angular/http';
import { BaseChartDirective } from 'ng2-charts';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild("baseChart") pieChartEl: BaseChartDirective;

  public doughnutChartLabels: string[] = [];
  public doughnutChartData: number[] = [];
  public doughnutChartType: string = 'doughnut';

  constructor(public navCtrl: NavController, public http: Http) {

  }

  ionViewDidLoad() {
    this.updateData();
  }

  public updateData() {
    this.http.get("/assets/datas.json").subscribe((res: Response) => {
          let jsons = res.json();
          let data = jsons[0];
          this.doughnutChartLabels.push("pos_percent");
          this.doughnutChartLabels.push("neg_percent");

          this.doughnutChartData.push(data.pos_percent);
          this.doughnutChartData.push(data.neg_percent);

          console.log(this.doughnutChartLabels);
          console.log(this.doughnutChartData);

          if(this.pieChartEl !== undefined){
            this.pieChartEl.ngOnDestroy();
            this.pieChartEl.chart = this.pieChartEl.getChartBuilder(this.pieChartEl.ctx);
          }
      });
  }
}

5: This is my result:

enter image description here

You can check my code in ionic3-chart I hope this could help :).

Sign up to request clarification or add additional context in comments.

2 Comments

Im trying to to make charts for every row. For example this is my data from phpmyadmin i.sstatic.net/yl68n.png . So there's four users and im trying to make pie chart for every user (four charts) based on their positive and negative tweet values.
Great Explaination bong!
0

You should do something like this:

export class YourClass {
   data; //Array of values

   constructor() { }

   ionViewDidLoad() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost/test/retrieve-data.php",true);
    xhr.onreadystatechnage = function() {
      var response = JSON.parse(xhr.responseText) //The JSON from your php server
      //configure your Json to an array (for the chart.js labels)
      this.data = //your configured json to array -> in Array 
      this.drawChart();
    } 

     xhr.send(null);


   }

   drawChart() {
    this.pieChartEl           = new Chart(this.pieChart.nativeElement,
      {
         type: 'pie',
         data: {
             labels: ["Positive","Negative"],
             datasets: [{
                 data                  : this.data, //here your data
                 duration              : 2000,
                 easing                : 'easeInQuart',
                 backgroundColor       : "rgba(54, 116, 152, 0.5)",
                 hoverBackgroundColor  : "rgba(160, 116, 152, 0.5)"
             }]
         },
         options : {
            maintainAspectRatio: false,
            layout: {
               padding: {
                  left     : 50,
                  right    : 0,
                  top      : 0,
                  bottom   : 0
               }
            },
            animation: {
               duration : 5000
            }
         }
      });



      this.chartLoadingEl = this.pieChartEl.generateLegend();

   }
}

3 Comments

Thank you for your response but nothing popped out. There are numbers of rows in my data and how do i fetch that row specifically.
Now I understand what you want to split the labels from the data... so therefore you should loop through the JSON (its key-value paired) and in your loop you can add the keys to the label array and and the values to the data array
Can you show me an example. Im sorry im new to this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.