【问题标题】:pie chart in highchart with dynamic data带有动态数据的 highchart 饼图
【发布时间】:2020-05-13 11:39:25
【问题描述】:

我想在 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】:

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

    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
        }]
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多