2016-11-23 91 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(); 

后设置的值。