Loreno Loreno - 1 month ago 100
Javascript Question

Google Charts and Angular 2 - a graph won't show

I'm learning Angular 2 and, as an exercise, I wanted to use Google Charts API.

Here's my component, in which I want to have a chart:

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


}


If I understand it correctly, I should only call this.loadGoogleChart() function, because inside of that there is a callback to drawChart(), so I do not need to call drawChart() myself. Unfortunately I don't see anything when I run it - the component only has the
<h1>
header, which I set in the template, but chart_div is just empty.

What am I doing wrong?
I saw a similar question: TypeError: google.visualization is undefined
but in that case the person who asked this got some results when console.log(google.visualization); was called. I don't see any message in my console.

So, I guess, drawChart() is never called. What's the reason for this?

Answer

On your line google.charts.setOnLoadCallback(() => this.drawChart); Can you change it to google.charts.setOnLoadCallback(() => this.drawChart());

Also there was a prevailing error that would say you can't reinitialize the chart for subsequent calls. I think it was updated but i haven't checked. Anyway you can always have this function checkloaded(): boolean { return !((typeof google === 'undefined') || (typeof google.visualization === 'undefined')); }

Which you would call to see if it's loaded previously so that subsequent calls to initialize it will be ignored.

Comments