【发布时间】:2016-09-28 06:33:06
【问题描述】:
我正在学习 Angular 2,作为练习,我想使用 Google Charts API。
这是我的组件,我想在其中有一个图表:
import { Component, OnInit } from '@angular/core';
import { WeatherAPIService } from './weatherAPI.service';
declare var google: any;
@Component({
selector: 'my-graphs',
template: `<h1>Charts for {{this.weatherAPIService.cityName}}</h1>
<div id="chart_div"></div>
`,
providers: [WeatherAPIService]
})
export class GraphsComponent implements OnInit {
//googleLoaded;
constructor(
private weatherAPIService: WeatherAPIService
) { }
drawChart () {
console.log(google.visualization);
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
loadGoogleChart() {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(() => this.drawChart);
}
ngOnInit(): void {
this.loadGoogleChart();
}
}
如果我理解正确的话,我应该只调用this.loadGoogleChart()函数,因为里面有一个drawChart()的回调,所以我不需要自己调用drawChart()。不幸的是,当我运行它时,我什么也没看到 - 该组件只有我在模板中设置的 <h1> 标头,但 chart_div 只是空的。
我做错了什么?
我看到一个类似的问题:TypeError: google.visualization is undefined
但在那种情况下,问这个问题的人在 console.log(google.visualization); 时得到了一些结果。被称为。我在控制台中没有看到任何消息。
所以,我猜,drawChart() 永远不会被调用。这是什么原因?
【问题讨论】:
标签: javascript angular typescript google-visualization