2016-09-28 70 views
3

我正在學習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()永遠不會被調用。這是什麼原因?

回答

4

工作線路上的想法 google.charts.setOnLoadCallback(() => this.drawChart); 可以將其更改爲google.charts.setOnLoadCallback(() => this.drawChart());

也有一個普遍的錯誤會說你不能重新初始化的後續調用圖表。我認爲它已更新,但我沒有檢查。無論如何,你總是可以擁有這個功能 checkloaded(): boolean { return !((typeof google === 'undefined') || (typeof google.visualization === 'undefined')); }

你會打電話來看看它是否以前加載,以便後續調用初始化它將被忽略。

1

我對Angular 2的生命週期並不熟悉,但是在Angular 1.x中Google Charts的廣泛應用,我不認爲你的代碼示例聽到反映了框架和庫之間配對的複雜性。

您將面臨的最大問題之一是您只能在谷歌圖表上調用一次負載。在它已經加載之後,如果你再次調用load,它將不會觸發你的回調。這意味着處理組件級別的加載通常不合適。如果您更改狀態並且該組件消失,則沒有任何事情處理加載程序服務已存在的事實。另外,你只能有一個回調,所以你有多個組件在同一時間加載,一個組件會覆蓋從谷歌圖表對方的回調,你會得到一個最後贏局面回調。

我無法就Angular 2的細節提供建議,因爲我沒有及時瞭解框架,但請記住,問題太複雜,無法在幾行代碼中處理。不過,我鼓勵你嘗試並努力。我在看到Angular Google Chart之前使用的一種哈克方法,是延遲角度引導,直到google圖表庫加載完畢。這樣,您可以對所有代碼都保持樂觀,並假設谷歌圖表庫已經加載。如果不將在角2