данные ионного дисплея чарджис из HTTP-запроса json - PullRequest
0 голосов
/ 13 ноября 2018

Я создаю ионное приложение для отображения панели мониторинга (круговой диаграммы) путем извлечения данных из запроса URL / HTTP.Вот мой код в .ts файле, вызывающий данные из URL, и мне удалось отобразить это в виде таблицы, используя e.g. {{ items.data }} в .html файле:

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);
          });
       }

Моя проблема в том, что я хочуполучить данные из ОДНОЙ строки и отобразить их на круговой диаграмме.Например, это одна строка, которую я хочу получить:

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

Я хочу отобразить круговую диаграмму, которая показывает значения pos_percent и neg_percent.

Вот чтоЯ делал и до сих пор застрял при вызове данных строки:

@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();
   }

Как мне получить эти данные?

Ответы [ 2 ]

0 голосов
/ 16 ноября 2018

Чтобы нарисовать PieChart из HTTP-запроса, пожалуйста, следуйте моим инструкциям ниже:

1 - Убедитесь, что вы установили Angular 2 charts и Charts.js, просто введите эту команду:

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

2- Зарегистрируйте 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- Добавьте тег Canvas в ваш HTML-файл, как показано ниже:

<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: Получить данные json и нарисовать на холсте:

Примечание: Я загружаю json из asset / datas.json через 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: Это мой результат:

enter image description here

Вы можете проверить мой код в ionic3-chart Надеюсь, это может помочь:).

0 голосов
/ 13 ноября 2018

Вы должны сделать что-то вроде этого:

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();

   }
}
...