2016-11-23 96 views
0

我正在使用Angular2和PrimeNG爲我的應用程序。 我有一個帶有圖表的儀表板。 我試圖更新到PrimeNG rc7(從rc5,他們解決了更新圖表的問題),但由於他們的更改,我不知道如何更新我的圖表,因爲它必須通過調用方法來完成。Angular 2/PrimeNg - 通過@ViewChild更新圖表

我讀過關於@ViewChild裝飾器,但我真的不知道如何使用它。

我chart.html:

<p-chart #linechart type="line" #linechart 
id="linechart" [data]="ntwdata" [options]="options"> 
</p-chart> 

我dashboard.ts:

import { NTWDATA } from '../resources/mock/chartdata'; 

import { UIChart } from 'primeng/primeng'; 

@Component({ 
    selector: 'my-dashboard', 
    templateUrl: 'dist/html/dashboard.component.html', 
}) 

export class DashboardComponent { 
    ntwdata = NTWDATA; 
    options: any; 

    constructor() { 

    } 

    ngOnInit() { 

     this.options = { 
      animation: false, 
      legend: { 
       display: true, 
       labels: { 
        boxWidth: 0, 
       } 

      }, 
      scales: { 
       yAxes: [{ 
        scaleLabel: { 
        display: true, 
        labelString: "ms" 
        }, 
        ticks: { 
        beginAtZero: true, 
        suggestedMax: 100, 
        } 

       }], 
       xAxes: [{ 
        ticks: { 
        beginAtZero: true, 
        maxTicksLimit: 6, 
        } 
       }] 

      } 
     } 
    } 
} 

的NTWDATA獲取更新每隔2.5秒,並與我的數據,一切都很好。

我的DashboardComponent是數據更新它的組件的子項。

父組件:

... 
setInterval(()=>{ 
    NTWDATA.push(//mydata) 
},2500); 
... 

我試圖@ViewChild添加到我的父母,像這樣:

@ViewChild("linechart") chart: UIChart 

然後我打電話給我的setInterval內刷新()梅索德:

setInterval(()=>{ 
    NTWDATA.push(//mydata) 
    this.chart.refresh(); 
},2500); 

但是this.chart是未定義的。

然後我試圖使用@ViewChild像這樣:

@ViewChild(Dashboard) dashcomp: Dashboard; 
setInterval(()=>{ 
     NTWDATA.push(//mydata) 
     this.dashcomp.chart.refresh(); 
    },2500); 

和我的孩子:

@ViewChild('linechart') chart: UIChart; 

正如我所說的,我從來沒有與RLY之前@ViewChild工作,我不認爲我如果現在明白這一點,那麼如果你們中的任何一個人有一個想法,我會很感激,如果你像我一樣愚蠢的話跟我說話! :D

在此先感謝!

+0

有關於在刷新()的一個例子; http://www.primefaces.org/primeng/#/chart –

+0

是的,但需要點擊一個按鈕刷新是我的儀表板絕對最壞的情況下。 :/因此我需要在我的父組件內的setInterval中調用它,所以我需要將我的孩子的圖表傳遞給父母,這就是我現在要查找的內容! – Faigjaz

+0

按鈕用於示例,在您的情況下,您確實需要@ViewChild,當您使用它時不會檢索它?哪一部分不起作用= –

回答

0

更新標籤數據集也。

this.chart.data.labels = labels; 
this.chart.data.datasets = datasets; 

嘗試在chart.refresh()上設置超時值,延遲時間爲幾秒100ms或1 200ms。

它適用於我。

0
<p-chart #chart type="bar" [data]="chartData" [options]="options"></p-chart> 

然後在角分量

import { UIChart } from "primeng/components/chart/chart"; 

獲取視圖REF(變化 「圖表」 參考)

@ViewChild("chart") chart: UIChart; 

this.chart.reinit(); 

後設置的值。