带有动态数据的高图中的饼图

问题描述 投票:0回答:1

我想在highchart中创建带有动态数据的饼图,所以我创建了此方法:

pieData :any=[];
getPiedata() {
 this.service.getSales().subscribe(data => {
    this.sales=data ;

    for (var i = 0; i < this.sales.length; i++){
       this.pieData.push({
          "name" : this.sales[i][this.pienames],
          "y" : this.sales[i][this.piepercent]
       })
     }
    ;
    console.log("pie",this.pieData);
    return JSON.stringify(this.pieData);
 })
}

这是PreparePiechart()方法:

PreparePiechart() {
this.pieOptions ={
   chart : {
     plotBackgroundColor: null,
     plotBorderWidth: null,
     plotShadow: false,
     type : 'pie'
   },
   title: {
     text: ''
   },

   series: [{
     name: 'Brands',
     colorByPoint: true,
     data: this.getPiedata()
   }]
 }}

期望的数据输入是一个像这样的json:

 [
  {name: "book1",
     y: 50
  }
  {name: "book2",
     y: 50
  }
  ]

这是ngOnInit():

ngOnInit() {
   this.PreparePiechart()
 }

但是我有一个空的饼图!如何解决呢?

arrays json angular highcharts
1个回答
0
投票

数据是异步的。您可以在收到数据后构建图表。尝试以下操作

getPiedata() {
 this.service.getSales().subscribe(data => {
    this.sales = data ;

    for (var i = 0; i < this.sales.length; i++){
      this.pieData.push({
        "name" : this.sales[i][this.pienames],
        "y" : this.sales[i][this.piepercent]
      })
    }
    console.log("pie",this.pieData);
    this.preparePiechart(JSON.stringify(this.pieData));  // <-- create chart options here
 })
}

preparePiechart(pieData: any) {
  this.pieOptions = {
    chart : {
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type : 'pie'
    },
    title: {
      text: ''
    },

    series: [{
      name: 'Brands',
      colorByPoint: true,
      data: pieData
    }]
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.