typescript 如何在 Angular 4 中放置 Google Chart

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45044101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:42:33  来源:igfitidea点击:

How do I put a Google Chart in Angular 4

angulartypescriptchartsgoogle-visualization

提问by Frederick John

How do you integrate a google chart in an angular 4 application?

您如何在 angular 4 应用程序中集成谷歌图表?

I read the answer to the SO question here, but I believe it's incomplete. Basically, I'm attempting the same strategy as the previous answer, using a GoogleChartComponent and another component that extends it. Two errors arise, the first is a missing call to super() for the child component and the second is the call to "new" in this code

我在这里阅读了 SO 问题的答案,但我认为它不完整。基本上,我正在尝试与上一个答案相同的策略,使用 GoogleChartComponent 和另一个扩展它的组件。出现了两个错误,第一个是子组件缺少对 super() 的调用,第二个是此代码中对“new”的调用

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

I'm getting the error "google.visualization.BarChart is not a constructor".

我收到错误“google.visualization.BarChart 不是构造函数”。

I see one of the comments also mentions the use of <ng-content>for data projection but it isn't clearly outlined.

我看到其中一条评论也提到了<ng-content>用于数据投影的用途,但没有明确概述。

In trying to ask a "good" question, here is my GoogleChartComponent:

在尝试提出一个“好”的问题时,这是我的 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);
  }
}

And my child component that extends it:

我的子组件扩展了它:

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

采纳答案by WhiteHat

google.visualization.BarChartis part of the 'corechart'package

google.visualization.BarChart'corechart'包裹的 一部分

need to change the load statement...

需要更改加载语句...

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

the 'bar'package is for the Materialchart version
which would be --> google.charts.Bar

'bar'包适用于材料图表版本
,即 -->google.charts.Bar

however, there are many config options that are not supported by Materialcharts...

但是,材料图表不支持许多配置选项......

for the full list of unsupported options --> Tracking Issue for Material Chart Feature Parity

有关不受支持的选项的完整列表 -->材料图表功能奇偶校验的跟踪问题

回答by ruruskyi

I believe there is better way to integrate Google Chart in Angular 4. Library ng2-google-chartsalready has GoogleChartComponent. Link to npm page describes pretty well how to use it. Below is example of component:

我相信有更好的方法可以在 Angular 4 中集成 Google Chart。库ng2-google-charts已经有 GoogleChartComponent。链接到 npm 页面很好地描述了如何使用它。以下是组件示例:

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

And your markup would look like this:

您的标记将如下所示:

<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>