我正在學習Angular 2,作爲練習,我想使用Google Charts API。
這裏是我的組件,其中我想有一個圖表:谷歌圖表和Angular 2 - 圖表不會顯示
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()永遠不會被調用。這是什麼原因?