无法将数据从 api 传递到 ng2-charts

Unable to pass data from api to ng2-charts

这是我在 component.ts 文件中的 ng2-chart 静态数据:

  public mbarChartLabels:string[] = ['June', 'July', 'August', 'September', 'October', 'November'];
  public barChartType:string = 'bar';
  public barChartLegend:boolean = true;

  public barChartColors:Array<any> = [
    {
      backgroundColor: 'rgba(95, 103, 245, 0.5)',
      borderColor: '#5200cc',
      pointBackgroundColor: 'rgba(105,159,177,1)',
      pointBorderColor: '#fafafa',
      pointHoverBackgroundColor: '#fafafa',
      pointHoverBorderColor: 'rgba(105,159,177)'
    },
    {
      backgroundColor: 'rgba(128, 237, 104,0.5)',
      borderColor: '#208000',
      pointBackgroundColor: 'rgba(77,20,96,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(77,20,96,1)'
    }
];
  public barChartData:any[] = [
    {data: [100,80,50,60,70,80], label: 'Approved'},
    {data: [60,80,80,30,40,90], label: 'Discounted'}
  ];

这是我从中接收数据的 Api 呼叫:

    this._auth.approved_discounted().toPromise().then((res:any)=>{
      if(res){
        this.approved = parseInt(res["Approved"])
        this.discounted = parseInt(res["Discounted"])

        console.log(this.approved+" "+this.discounted)
       }
    });

在这里,我试图将 this.approved 和 this.discounted 数据插入到 ng2-chart 但它正在接收它。如何将我的 API 数据合并到 ng2-chart 中?

也许您的 html 在接收数据之前就已呈现。您可以使用布尔值等待数据并在它之后加载 html 个元素。

this.loadData = true;
this._auth.approved_discounted().toPromise().then((res:any)=>{
      if(res){
        this.approved = parseInt(res["Approved"])
        this.discounted = parseInt(res["Discounted"])

        console.log(this.approved+" "+this.discounted)
       }
       this.loadData = false;
    });

在你的 html:

<canvas *ngIf="!loadData"></canvas> // 或您的 "chart" 标签

题外话:

I don't know why you use Promise (probably you come from plain js or React/AngularJs). Try to use Observables, this is specific for Angular. And namings ... "approved_discounted", this is not for Angular, this is for php or any other. Use approvedDiscounted - Angular Coding Style Guide