angular - 无法使用 API 获取的数据初始化 ngx-charts

标签 angular typescript charts time-series ngx-charts

我在尝试初始化使用 ngx-charts 构建的图表时遇到了一些困难时期使用 API 获取数据。

我构建了一个休息 api,在适当的调用时,吐出一些时间序列数据。

{
    "prices": [
        {
            "item": "1",
            "price": 2,
            "estimated": 2.1,
            "date": [
                2012,
                8,
                16
            ]
        },
        {
            "item": "1",
            "price": 3,
            "estimated": 4.1,
            "date": [
                2012,
                9,
                16
            ]
        },
        {
            "item": "1",
            "price": 5,
            "estimated": 7.1,
            "date": [
                2012,
                10,
                16
            ]
        }
    ]
}

我构建了 price.model.ts 来正确处理它,它工作得很好

export class PriceModel {
    public id: string;
    public price: number;
    public estimated: number;
    public date: number[];

    constructor(
         id: string,
         price: number,
         estimated: number,
         date: number[]
    ) {
        this.id = id;
        this.price = price;
        this.estimated = estimated;
        this.date = date;
     }
}

然后,我设置了我的 details.component.ts 以执行此类 api 调用、获取数据、解析数据并将其呈现到图表中。

import { Component } from '@angular/core';
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { Http } from '@angular/http';

/** App Models **/
import { PriceModel } from '../../shared/components/prices/price.model';
import { ChartDataModel } from '../../shared/components/prices/chart-data.model';

@Component({
  selector: 'app-details',
  templateUrl: './details.page.html',
  providers: [NgxChartsModule]
})

export class DetailsPage {

  private sub: any;
  private prices: PriceModel[];
  ngxData: ChartDataModel = {
    data: [
      {
        name: 'prices',
        series: []
      },
      {
        name: 'forecast',
        series: []
      }
    ]
  };

  view: any[] = [1000, 750];

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Dates';
  showYAxisLabel = true;
  yAxisLabel = 'Prices';

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  // line, area
  autoScale = true;

  constructor(private _http: Http) {
    console.log(this.ngxData.data);
    Object.assign(this.ngxData);
  }

  ngOnInit() {
    this.sub = this._http.get('someroute').subscribe((prices) => {
        this.prices = prices.json().prices;
        let currData;
        this.prices.map((p) => {
          currData = new Date(p.date[0], p.date[1], p.date[2]);
          this.ngxData.data[0].series.push({ name: currData.getTime().toString(), value: p.price });
          this.ngxData.data[1].series.push({ name: currData.getTime().toString(), value: p.estimated });
        });
      }, (err) => {
        console.log(err);
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

我的 ChartDataModel.ts 定义为

export class ChartDataModel {
    public data: SerieModel[];
    constructor(data:  SerieModel[]) {
        this.data = data;
    }
}

export class SerieModel {
    public name: string;
    public series: SeriersChildModel[];
    constructor(name:  string, series: SeriersChildModel[]) {
        this.name = name;
        this.series = series;
    }
}

export class SeriersChildModel {
    public name: string;
    public value: number;
    constructor(name:  string, value: number) {
        this.name = name;
        this.value = value;
    }
}

最后,这是我的 details.page.html

<ngx-charts-line-chart
  [view]="view"
  [scheme]="colorScheme"
  [results]="ngxData.data"
  [gradient]="gradient"
  [xAxis]="showXAxis"
  [yAxis]="showYAxis"
  [legend]="showLegend"
  [showXAxisLabel]="showXAxisLabel"
  [showYAxisLabel]="showYAxisLabel"
  [xAxisLabel]="xAxisLabel"
  [yAxisLabel]="yAxisLabel"
  [autoScale]="autoScale">
</ngx-charts-line-chart>

Object.assign 之前记录 this.ngxData.data 打印一切正常

enter image description here

但我最终得到了以下结果

enter image description here

我遵循可用的示例 here但最终没有实际显示任何数据。

我不明白为什么,即使数据按照图书馆的要求格式化,数据也没有显示。

我做错了什么?是构造函数初始化错误导致的吗?

最佳答案

您的问题是关于通过 ngxData.data[x]series.push() 修改系列未通过更改检测识别。

重新分配 ngxData.data 应该被检测到:this.ngxData.data = [...this.ngxData.data]

ngOnInit() {     
    this.sub = this._http.get('someroute').subscribe((prices) => {
        this.prices = prices.json().prices;
        let currData;
        this.prices.map((p) => {
          currData = new Date(p.date[0], p.date[1], p.date[2]);
          this.ngxData.data[0].series.push({ name: currData.getTime().toString(), value: p.price });
          this.ngxData.data[1].series.push({ name: currData.getTime().toString(), value: p.estimated })
        });
        //your solution
        this.ngxData.data = [...this.ngxData.data];
      }, (err) => {
        console.log(err);
    });
  }

我设法添加了一个 plunker https://plnkr.co/edit/JSTcS4FnJ5dshAldLWPL?p=preview

关于angular - 无法使用 API 获取的数据初始化 ngx-charts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532244/

相关文章:

typescript - 为什么 typescript 中的强类型丢失为 `any`?

javascript - 自定义验证器无法访问 Angular 6 Reactive 表单中的表单

javascript - ChartJs 自定义工具提示位置

来自共享模块的 Angular 8 指令不起作用

Angular2 ReactiveFormsControl : how to bind radio buttons?

reactjs - React 和 TypeScript 上传文件输入错误

c# - Xamarin Forms 可移植应用程序上未显示 OxyPlot 图表

javascript - 在 Angularjs 中准备金字塔图

javascript - 错误 下拉列表验证错误 : mat-form-field must contain a MatFormFieldControl.

angular - Observable.forkJoin 和数组参数