Búsqueda de sitios web

typescript - ¿Cómo pongo un gráfico de Google en Angular 4?


¿Cómo se integra un gráfico de Google en una aplicación Angular 4?

Leí la respuesta a la pregunta de SO aquí, pero creo que está incompleta. Básicamente, estoy intentando la misma estrategia que la respuesta anterior, usando un GoogleChartComponent y otro componente que lo extiende. Surgen dos errores, el primero es una llamada faltante a super() para el componente hijo y el segundo es la llamada a "new" en este código

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

Estoy recibiendo el error "google.visualization.BarChart no es un constructor".

Veo que uno de los comentarios también menciona el uso de <ng-content> para la proyección de datos, pero no está claramente explicado.

Al intentar hacer una pregunta "buena", aquí está mi GoogleChartComponent:

export class GoogleChartComponent implements OnInit {
  private static googleLoaded: any;
  constructor() {
    console.log('Here is GoogleChartComponent');
  }

  getGoogle() {
    return google;
  }

  ngOnInit() {
    console.log('ngOnInit');
    if (!GoogleChartComponent.googleLoaded) {
      GoogleChartComponent.googleLoaded = true;
      google.charts.load('current', {
        'packages': ['bar']
      });
      google.charts.setOnLoadCallback(() => this.drawGraph());
    }
  }

  drawGraph() {
      console.log('DrawGraph base class!!!! ');
  }

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

  createDataTable(array: any[]): any {
      return google.visualization.arrayToDataTable(array);
  }
}

Y mi componente hijo que lo extiende:

@Component({
  selector: 'app-bitcoin-chart',
  template: `
   <div id="barchart_material" style="width: 700px; height: 500px;"></div>
  `,
  styles: []
})
export class BitcoinChartComponent extends GoogleChartComponent  {
 private options;
  private data;
  private chart;
  // constructor() {
  //   super();
  //   console.log('Bitcoin Chart Component');
  // }
  drawGraph() {
    console.log('Drawing Bitcoin Graph');
    this.data = this.createDataTable([
     ['Price', 'Coinbase', 'Bitfinex', 'Poloniex', 'Kraken'],
     ['*', 1000, 400, 200, 500]
    ]);

    this.options = {
     chart: {
                    title: 'Bitcoin Price',
                    subtitle: 'Real time price data across exchanges',
                },
                bars: 'vertical' // Required for Material Bar Charts.
    };

    this.chart = this.createBarChart(document.getElementById('barchart_material'));
    this.chart.draw(this.data, this.options);
  }
}

Respuesta #1

Creo que hay una mejor manera de integrar Google Chart en Angular 4. La biblioteca ng2-google-charts ya tiene GoogleChartComponent. El enlace a la página de npm describe bastante bien cómo usarlo. A continuación se muestra un ejemplo de componente:

import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {ViewChild} from '@angular/core';

import {GoogleChartComponent} from 'ng2-google-charts';

// needed for advanced usage of ng2-google-charts
import {HostListener} from '@angular/core';

@Component({
  selector: '[your-widget]',
  templateUrl: './your-widget.html',
  encapsulation: ViewEncapsulation.None
})
export class YourWidget implements OnInit {

  // type GoogleChartComponent and import for it can be ommited
  @ViewChild('your_chart') chart: GoogleChartComponent;

  // shows spinner while data is loading
  showSpinner: boolean;

  public chartData = {
    chartType: 'AnyChartType', // your type
    dataTable: [
      ['Col1', 'Col2']
    ],
    options: {}
  };

  constructor() {
  }

  ngOnInit(): void {

    this.showSpinner = true;
    this.yourService.getData()
          .subscribe((data) => {
            //this.data = data;
            this.processYourData();
            this.showSpinner = false;
        });
      }

  private processYourData() {
  }

  // advanced usage of chart
  //   in this case redraw function on window:resize event
  @HostListener('window:resize', ['$event'])
  onWindowResize(event: any) {
    // console.log(event.target.innerWidth);
    // Make sure you don't call redraw() in ngOnInit()
    //   - chart would not be initialised by that time, and
    //   - this would cause chart being drawn twice
    this.chart.redraw(); 
  }
}

Y tu marcado se vería así:

<header class="widget-handle">
  <h5>Widget Title</h5>
  <div class="widget-controls">
    <a title="Refresh">
      <i *ngIf="showSpinner" class="fa fa-refresh fa-spin"></i>
    </a>
  </div>
</header>

<div class="widget-body">
  <google-chart #your_chart [data]="chartData" *ngIf="!showSpinner">
  </google-chart>
</div>

Respuesta #2

google.visualization.BarChart es parte del paquete 'corechart'

necesito cambiar la instrucción de carga...

  google.charts.load('current', {
    'packages': ['corechart']
  });

el paquete 'bar' es para la versión de gráfico Material
que sería --> google.charts.Bar

sin embargo, hay muchas opciones de configuración que no son compatibles con los gráficos Material...

para la lista completa de opciones no compatibles --> Seguimiento del problema de paridad de funciones de gráficos de materiales

Artículos relacionados