4

“我正在使用 Angular 6。我在仪表板上有一个圆环图,当我转到其他页面并返回圆环图显示时,它的数据第一次没有加载。刷新时数据也消失了。我正在获取 api 数据在解析器的帮助下。图形和其他组件被加载,但不是这个图表。在给定静态数据时它工作得很好。

import { Component, OnInit } from '@angular/core';
import * as Chartist from 'chartist';
import { ChartType, ChartEvent } from "ng-chartist/dist/chartist.component";
import { ActivatedRoute } from '@angular/router';

var obtained: any

export interface Chart {
  type: ChartType;
  data: Chartist.IChartistData;
  options?: any;
  responsiveOptions?: any;
  events?: ChartEvent;
}

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

    total: any
    obtained: any
    public dataApi: any;       

  constructor(private route:ActivatedRoute) {          
  }


  ngOnInit() {   

    this.dataApi = this.route.snapshot.data['dashboard'];


    if(this.dataApi.status_code==1)
    {                                  
        obtained = this.dataApi.data1.obtained                                                    

    }         

  }

dash: any ={       
    "series": [
        {
            "name": "progress",
            "className": "ct-grey",
            "value":  50-obtained
    },
      {
        "name": "done",
        "className": "ct-allow",
        "value":  obtained
      }


    ]       
}

DonutChart: Chart = {
    type: 'Pie',
    data: this.dash,
    options: {
        donut: true,
        startAngle: 0,   
        labelInterpolationFnc: function (value) {           
            return obtained;
        }    
    },
    events: {
        draw(data: any): void {
            if (data.type === 'label') {
                if (data.index === 0) {
                    data.element.attr({
                        dx: data.element.root().width() / 2,
                        dy: data.element.root().height() / 2
                    });
                } else {
                    data.element.remove();
                }
            }

        }
    }
};

}
4

3 回答 3

2

我刚刚得到了 angular 6 的图表工作。我使用 js 来解决这个问题,而不是 ts。

安装这些:

npm i chartist --save
npm i @types/chartist --save-dev

然后在 angular.json 中添加 css 和 js

"scripts": ["node_modules/chartist/dist/chartist.min.js"],
"styles": ["node_modules/chartist/dist/chartist.min.css"]

在 app.component

declare let $: any;
import * as Chartist from 'chartist';

...

ngOnInit() {
    const me = this;

    setTimeout(() => {
      me.loadChart();
    }, 500);
}

loadChart() {
  $(function() {
    var chart = new Chartist.Pie('.ct-chart', {
      series: [10, 20, 50, 20, 5, 50, 15],
      labels: [1, 2, 3, 4, 5, 6, 7]
    }, {
      donut: true,
      showLabel: false
    });

    chart.on('draw', function(data) {
      if(data.type === 'slice') {
        // Get the total path length in order to use for dash array animation
        var pathLength = data.element._node.getTotalLength();

        // Set a dasharray that matches the path length as prerequisite to animate dashoffset
        data.element.attr({
          'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
        });

        // Create animation definition while also assigning an ID to the animation for later sync usage
        var animationDefinition = {
          'stroke-dashoffset': {
            id: 'anim' + data.index,
            dur: 1000,
            from: -pathLength + 'px',
            to:  '0px',
            easing: Chartist.Svg.Easing.easeOutQuint,
            // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
            fill: 'freeze'
          }
        };

        // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
        if(data.index !== 0) {
          animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
        }

        // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
        data.element.attr({
          'stroke-dashoffset': -pathLength + 'px'
        });

        // We can't use guided mode as the animations need to rely on setting begin manually
        // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
        data.element.animate(animationDefinition, false);
      }
    });

    // For the sake of the example we update the chart every time it's created with a delay of 8 seconds


  });
}

在 app.html 中

<div class="ct-chart ct-perfect-fourth"></div>

转到https://gionkunz.github.io/chartist-js/examples.html并将其中的任何示例图表复制粘贴到您的应用程序中。它应该可以正常工作=)

于 2018-09-30T10:35:35.700 回答
0

我想将它封装到一个可以绑定数据的组件中,所以我这样做了:

npm install chartist --save
npm install @type/chartist --save-dev

创建一个简单的组件

/* bar-char.component.ts' */
import {  AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core';
import { Bar, IChartistBarChart, IChartistData } from 'chartist';

@Component({
  selector: 'bar-chart',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None, // <-- Very important otherwise style imported from node_modules wont apply
  template: `<div #elt></div>`,
  styleUrls: [
    './bar-char.component.scss'
  ]
})
export class BarChartComponent implements AfterViewInit {
  @Input() public data: IChartistData;
  public chart: IChartistBarChart;

  @ViewChild('elt', { static: false })
  private elt: ElementRef;

  public ngAfterViewInit(): void {
    if (this.data) {
      this.chart = new Bar(this.elt.nativeElement, this.data);
    }
  }
}

然后在组件的scss中我们从chartist导入样式

/* bar-char.component.scss' */
@import '~chartist/dist/scss/chartist.scss'; /* <-- import styles from chartist node_modules */

我们会这样使用它:

/* app.component.ts */
@Component({
  selector: 'pms-root',
  template: `<bar-chart [data]="myChartData"></bar-chart>`
})
export class AppComponent {
  public myChartData: IChartistData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      series: [
      [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
      [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
    ]
  };

/* Don't forget to declare it in your module */

@NgModule({
  declarations: [
    BarChartComponent, // ...

在角度 8 上测试

于 2019-11-15T13:54:49.067 回答
0

我有同样的问题,我得到了它的工作。手表似乎只在外部数据对象上。如果您只是更改基础系列和标签,它不会触发图表的重绘。

但是,如果您替换图表对象中的整个数据对象,则会触发重绘。为我工作。

此外,如果您仍然遇到问题,您可以随时直接调用 API,如下所示:

         var chartDom = document.getElementById("mychart");
         if(chartDom && chartDom["__chartist__"])
            chartDom["__chartist__"]["update"]();
于 2019-01-30T11:55:45.453 回答