使用HttpClient将google datatable提取到Angular组件失败

使用HttpClient将google datatable提取到Angular组件失败,angular,charts,google-visualization,angular-httpclient,Angular,Charts,Google Visualization,Angular Httpclient,我试图在我的Angular web应用程序中使用google图表,但从控制器获取数据时遇到问题。考虑下面的谷歌图表组件的尝试。当我使用注释掉的google.visualization数据表代码时,该组件工作正常。我设置了一个控制器,从服务器返回类似的数据。我在下面的代码中展示了一个返回数据的示例。当我尝试使用获取的数据时,图表组件失败了,它只会不产生任何结果。我的调试尝试表明我对HttpClient的理解非常差。考虑NGnIIT顶部的两个HTTPGET语句;第一个显示了响应对象的控制台输出,它看

我试图在我的Angular web应用程序中使用google图表,但从控制器获取数据时遇到问题。考虑下面的谷歌图表组件的尝试。当我使用注释掉的google.visualization数据表代码时,该组件工作正常。我设置了一个控制器,从服务器返回类似的数据。我在下面的代码中展示了一个返回数据的示例。当我尝试使用获取的数据时,图表组件失败了,它只会不产生任何结果。我的调试尝试表明我对HttpClient的理解非常差。考虑NGnIIT顶部的两个HTTPGET语句;第一个显示了响应对象的控制台输出,它看起来非常像我期望的从控制器返回的json创建的对象。第二个http.get导致this.chartData未定义,这似乎是问题的核心。有什么提示吗

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var google: any;

// Reference:
//  https://stackoverflow.com/questions/37542408/angular2-google-charts-how-to-integrate-google-charts-in-angular2

@Component({
selector: 'google-chart',
templateUrl: './google-chart.component.html',
styleUrls: ['./google-chart.component.css']
})
export class GoogleChartComponent implements OnInit {
    private chartData: any;

constructor(
    private http: HttpClient) {
}

ngOnInit() {

    this.http.get('api/BinomialResult/GetGoogleChartData')
        .subscribe(response => console.log("response:",response));

    this.http.get('api/BinomialResult/GetGoogleChartData')
        .subscribe(response => this.chartData = response);

    // Load the Visualization API and the chart package.
    google.charts.load('current', { 'packages': ['corechart'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);

    // Callback that creates and populates a data table, 
    // instantiates the chart, passes in the data and
    // draws it.
    function drawChart(this: any) {

        // (1) Create the data table from an array.

        //var dataTable = google.visualization.arrayToDataTable([
        //  ['X', 'Prior', 'Posterior'],
        //  [0.0, 5.000, 0.000],
        //  [0.1, 1.061, 0.026],
        //  [0.2, 0.795, 0.347],
        //  [0.3, 0.694, 1.180],
        //  [0.4, 0.649, 2.152],
        //  [0.5, 0.636, 2.586],
        //  [0.6, 0.649, 2.152],
        //  [0.7, 0.694, 1.180],
        //  [0.8, 0.795, 0.347],
        //  [0.9, 1.061, 0.026],
        //  [1.0, 5.000, 0.000]
        //]);

        // (2) Create the data table explicitly

        //var dataTable = new google.visualization.DataTable();
        //var newData = [
        //  ['X', 'Prior', 'Posterior'],
        //  [   0.0,  10.07,  4.169E-11 ],
        //  [   0.1,  1.061,  0.026 ],
        //  [   0.2,  0.795,  0.347 ],
        //  [   0.3,  0.694,  1.180 ],
        //  [   0.4,  0.649,  2.152 ],
        //  [   0.5,  0.636,  2.586 ],
        //  [   0.6,  0.649,  2.152 ],
        //  [   0.7,  0.694,  1.180 ],
        //  [   0.8,  0.795,  0.347 ],
        //  [   0.9,  1.061,  0.026 ],
        //  [   1.0,  10.07,  4.169E-11 ]
        //];

        //// determine the number of rows and columns.
        //var numRows = newData.length;
        //var numCols = newData[0].length;

        //// addd the columns
        //for (var i = 0; i < numCols; i++)
        //  dataTable.addColumn('number', newData[0][i]);

        //// add the rows.
        //for (var i = 1; i < numRows; i++)
        //  dataTable.addRow(newData[i]);           

        // (3) Create the data table from json

        var dataTable = new google.visualization.arrayToDataTable(this.chartData);

        // Set chart options

        var options = {
            title: 'Google Line Chart Example',
            width: 600,
            height: 370,
            chartArea: { left: 40, top: 30},
            curveType: 'none',
            hAxis: {
                title: 'P\n\n\n\n',  // https://www.webtoolhub.com/tn561380-xhtml-characters-list.aspx?type=script&category=greek-coptic
                textStyle: { 
                    //color: '#01579b',
                    //fontSize: 20,
                    fontName: 'Arial',
                    bold: false,
                    italic: false
                },
                titleTextStyle: {
                    //color: '#01579b',
                    //fontSize: 16,
                    fontName: 'Arial',
                    bold: false,
                    italic: false
                }
            },
            vAxis: {
                title: 'Likelihood',
                textStyle: {
                    //color: '#1a237e',
                    //fontSize: 24,
                    bold: false,
                    italic: false
                },
                titleTextStyle: {
                    //color: '#1a237e',
                    //fontSize: 24,
                    bold: false,
                    italic: false
                }
            },
        };

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));

        chart.draw(dataTable, options);
    }
  }
}

我已经应用了换行和缩进,以使返回的数据更易于阅读。返回的json数据是使用C#的Google.DataTable.Net.Wrapper生成的,该包装器作为Nuget包提供。

在将数据分配给
this.chartData
之前,图表代码可能正在运行

您可能应该在
subscribe
函数中包含图表代码

尝试以下结构

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var google: any;

// Reference:
//  https://stackoverflow.com/questions/37542408/angular2-google-charts-how-to-integrate-google-charts-in-angular2

@Component({
  selector: 'google-chart',
  templateUrl: './google-chart.component.html',
  styleUrls: ['./google-chart.component.css']
})

export class GoogleChartComponent implements OnInit {
  private chartData: any;

  constructor(
    private http: HttpClient) {
  }

  ngOnInit() {
    this.http.get('api/BinomialResult/GetGoogleChartData').subscribe(function (response) {
      google.charts.load('current', {
        packages: ['corechart']
      }).then(function () {
          var dataTable = new google.visualization.DataTable(response);

          var options = {
              title: 'Google Line Chart Example',
              width: 600,
              height: 370,
              chartArea: { left: 40, top: 30},
              curveType: 'none',
              hAxis: {
                  title: 'P\n\n\n\n',
                  textStyle: {
                      fontName: 'Arial',
                      bold: false,
                      italic: false
                  },
                  titleTextStyle: {
                      fontName: 'Arial',
                      bold: false,
                      italic: false
                  }
              },
              vAxis: {
                  title: 'Likelihood',
                  textStyle: {
                      bold: false,
                      italic: false
                  },
                  titleTextStyle: {
                      bold: false,
                      italic: false
                  }
              },
          };

          var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));
          chart.draw(dataTable, options);
      });
    });
  }
}
注意:您使用的json将直接创建一个数据表,
不需要helper方法
arrayToDataTable

var dataTable = new google.visualization.DataTable(response);

怀特哈特发现了这个问题。是 啊我想出了类似的办法。诀窍不仅是在subscribe回调中分配数据,而且在数据可用之前不给googlecharts drawChart函数,否则可能会出现可怕的无列错误消息。和WhiteHat差不多

以下是我确定的代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var google: any;

@Component({
selector: 'google-chart',
templateUrl: './google-chart.component.html',
styleUrls: ['./google-chart.component.css']
})
export class GoogleChartComponent implements OnInit {

public chartData: any;
public dataTable: any;

constructor(
    private http: HttpClient) {
}

ngOnInit() {

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

    this.http.get('api/BinomialResult/GetGoogleChartData')
        .subscribe((response: any) => {
            this.chartData = response;
            this.dataTable = new google.visualization.DataTable(this.chartData);
            google.charts.setOnLoadCallback(this.drawChart.bind(this));
        });
}
private drawChart(this: any) {

    // Set chart options
    var options = {
        title: 'Google Line Chart Example',
        width: 600,
        height: 370
    };

    var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));

    chart.draw(this.dataTable, options);
  }

}

代码无法识别
this
此处-->
this.http
已更新代码,但未了解您确定的问题(this.http为何未定义)。我在HttpClient方面的困难没有得到解决,可以说,只是转到了下一步。我修改了我的问题,指出了新的症结所在。是的,这就是问题所在。我提出了一个类似的解决方案,当我回到这里发帖时,你已经回答了。在我升级到Angular 8和dotnet sdk 3.1之前,我上面发布的方法工作得很好。我不知道为什么,但我的坏了,你的方法仍然有效。所以我接受了你的回答。这就提出了一个更大的问题:如何构建一个有用的Google图表库来避免这个加载问题。尚未找到可用于异步数据加载的示例。我自己的尝试仍然是脆弱的,只有在初始加载后才能起作用。如果你遇到一个好例子,请给我指一下。
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare var google: any;

@Component({
selector: 'google-chart',
templateUrl: './google-chart.component.html',
styleUrls: ['./google-chart.component.css']
})
export class GoogleChartComponent implements OnInit {

public chartData: any;
public dataTable: any;

constructor(
    private http: HttpClient) {
}

ngOnInit() {

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

    this.http.get('api/BinomialResult/GetGoogleChartData')
        .subscribe((response: any) => {
            this.chartData = response;
            this.dataTable = new google.visualization.DataTable(this.chartData);
            google.charts.setOnLoadCallback(this.drawChart.bind(this));
        });
}
private drawChart(this: any) {

    // Set chart options
    var options = {
        title: 'Google Line Chart Example',
        width: 600,
        height: 370
    };

    var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));

    chart.draw(this.dataTable, options);
  }

}