[英]Pass array from parent to child component in Angular
I'm using the ng2-chart library and I want to pass the information of a parent component to the child comonent.我正在使用 ng2-chart 库,我想将父组件的信息传递给子组件。 I get the information from an API that provides me with the data.我从为我提供数据的 API 获得信息。 But it is not loading the information:但它没有加载信息:
export class PruebasComponent implements OnInit {
lineChartData: ChartDataSets[];
lineChartLabels: Label[];
In the ngOnInit
I get the data在ngOnInit
我得到数据
ngOnInit() {
this.loading = true;
this.datos.getDesktopLimit().subscribe(
res => {
this.loading = false;
this.data = [res];
this.dataSource = this.data[0];
this.barChartData = true;
this.getFilter(this.dataSource);
}
)
}
and through the getFilter ()
function I can modify the data I want to send:并通过getFilter ()
function 可以修改我要发送的数据:
getFilter(data) {
data.sort((a, b) => a.id - b.id);
for (let entry of data) {
this.date.push(moment(entry.created).format('DD-MM-YYYY HH:mm'))
this.time.push(entry.total_load_time * 0.001)
}
this.lineChartData = [{ data: this.time, label: 'Time Render' }] /* [ { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' }] */;
this.lineChartLabels = this.date;
this.loading = false
}
[datasets]
sends the empty data [datasets]
发送空数据
<app-graphic [datasets]="lineChartData" [labels]="lineChartLabels"></app-graphic>
The problem is that you are passing the data to the child component before you receive the data and finish of transform it.问题是您在接收数据并完成转换之前将数据传递给子组件。
You should use *ngIf
in the <app-graphic>
until you finish getting the data and transform it:您应该在<app-graphic>
中使用*ngIf
,直到您完成获取数据并对其进行转换:
<app-graphic [datasets]="lineChartData" [labels]="lineChartLabels" *ngIf="lineChartData && lineChartLabels"></app-graphic>
I think with the *ngIf
the should work.我认为使用*ngIf
应该可以工作。
With some external components, it important to never send null when they are expecting a list.对于一些外部组件,重要的是不要在他们期待一个列表时发送 null。
So try:所以试试:
lineChartData: ChartDataSets[] = [];
lineChartLabels: Label[] = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.