首页 > 解决方案 > 如何通过以角度订阅圆环图从服务中分配动态数据?

问题描述

如何将数据动态分配给甜甜圈数据。如何通过 ngOnIt 上的订阅方法将来自服务文件的数据链接到甜甜圈数据。这样我就可以将 multisetdata 链接到一个动态的数据而无需对其进行硬编码 我还可以通过链接到 ctx.fillText 来动态显示中心数据吗

我的 .ts 文件

  public doughnutChartLabels: Label[] = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales'];
  public doughnutChartData: MultiDataSet = [
   
   
  ];
 radius = length * Math.SQRT2 / 2;
  colors= [
    {
      backgroundColor: [
        '#E6B01C',
        '#1454A3',
        '#22C3BD',
        'yellow'
      ]
    }
  ];
  public doughnutChartType: ChartType = 'doughnut';
  public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [{
    beforeDraw(chart) {
      const ctx = chart.ctx;
      const txt = '26';

      //Get options from the center object in options
      const sidePadding = 60;
      const sidePaddingCalculated = (sidePadding / 100) * (this.radius * 2)

      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      const centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      const centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

      //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
      const stringWidth = ctx.measureText(txt).width;
      const elementWidth = (this.radius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      const widthRatio = elementWidth / stringWidth;
      const newFontSize = Math.floor(30 * widthRatio);
      const elementHeight = (this.radius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      // const fontSizeToUse = Math.min(newFontSize, elementHeight);

      // ctx.font = fontSizeToUse + 'px Arial';
      ctx.fillStyle = 'blue';

      // Draw text in center
      ctx.fillText('26', centerX, centerY);
    }
  }];

  constructor(private roleService:RoleDashboardService) { }

  ngOnInit() {
    this.roleService.getWidget).subscribe((data)=>{
      console.log(data)
      this.doughnutChartData
      console.log(this.doughnutChartData)
    })
  }

  // events
  public chartClicked({ event, active }: { event: MouseEvent, active: {}[] }): void {
    console.log(event, active);
  }

  public chartHovered({ event, active }: { event: MouseEvent, active: {}[] }): void {
    console.log(event, active);
  }

标签: htmlangularchart.jsng2-charts

解决方案


取决于您使用的后端。例如,如果您通过 php 从 mysql 获取数据,您将使用以下内容:

array1=[];
array2=[];

//api call on backend

this.http.get('http://localhost/angular9/chartData.php').subscribe(data => {
//create array and push the data
this.array1.push(data);
  //assign this array to another arraya and map it     
  this.array2 = this.array1[0].map(function(item, keys) {
   var mixarrayy = Object.keys(item).concat(Object.values(item));
  return mixarrayy;

    });

推荐阅读