typescript - Angular 4: Problema con datos dinámicos en DoughnutChart de PrimeNg
Recientemente he estado trabajando en gráficos de PrimeNG, y estoy utilizando DoughnutChart proporcionado por PrimeNG. Quiero pasar un valor numérico almacenado en una variable como datos en el archivo ts para este gráfico, pero no muestra nada en la interfaz de usuario, mientras que si los datos son estáticos funciona perfectamente. Este es el código correspondiente:
1.)Trabajando uno:-
this.invoicedata = {
labels: ['InvoiceQty', 'TotalQty'],
datasets: [
{
data: [50, 50],
backgroundColor: [
"#ff9800",
"#ffffff",
],
hoverBackgroundColor: [
"#ff9800",
"#ffffff",
]
}]
}
2.) No funcional:-
this.invoicedata = {
labels: ['InvoiceQty', 'TotalQty'],
datasets: [
{
data: [this.pICompletionPercentage, this.PIPendingpercent],
backgroundColor: [
"#ff9800",
"#ffffff",
],
hoverBackgroundColor: [
"#ff9800",
"#ffffff",
]
}]
}
Esto es HTML para lo mismo:-
<div class="row">
<p-chart type="doughnut" [data]="invoicedata" width="150px"></p-chart>
<p class="text-center">Invoiced- {{pICompletionPercentage}}%</p>
</div>
Respuesta #1
El problema probablemente sea que configuraste tu invoiceData antes de que tu llamada al servicio haya terminado. Dado que tendrás que esperar un tiempo para poblar invoiceData, es posible que también quieras retrasar la inicialización del gráfico de primeng. Puedes lograr esto con *ngIf.
Entonces, puedes hacer algo así
Tu.componente.ts
@Component({
selector: 'your-comp',
template: `
<p-chart *ngIf="invoiceData" type="doughnut" [data]="invoiceData">
</p-chart>
`
})
export class YourComponent implements OnInit {
invoiceData;
constructor(private someService: SomeService) {}
ngOnInit() {
this.getData();
}
getData() {
this.someService
.getData()
.subscribe(resp => {
// here you can set your data the way you want.
this.invoiceData = resp;
})
}
}
