【问题标题】:use of JSON data in ng2-charts在 ng2-charts 中使用 JSON 数据
【发布时间】:2019-08-13 19:35:26
【问题描述】:

[如果我不清楚描述情况和我想要什么,请告诉我如何改进这个问题以便您更好地理解]

我正在更改我们之前构建的 Angular 应用程序中的图表。我们正在使用 ng2-charts。之前我们使用了两个 JSON/数组。但是 REST 服务(我无法更改,因为它来自第 3 方服务)现在已更改。新的 REST 服务如下所示。我尝试使用一个 JSON。当我的输入是 .ts 文件本身中的硬编码 json 时,我能够看到图表。

但是当我尝试从 REST(GET) 调用中获取 JSON 时,我遇到了困难。

仅供参考:当我在控制台中打印 JSON 时,我可以看到它。请看图

我收到错误:

无法读取未定义的属性“数据”

以下是两个 stackblitz 示例。 第一个是硬编码的 JSON,第二个来自 REST 调用:

https://stackblitz.com/edit/ng2-charts-line-template-iq1mia

https://stackblitz.com/edit/ng2-charts-line-template-voazjk

public summaryboardJson: Summaryboard[];
  public lineChartLegend = true;
  public lineChartType = 'line';
  public lineChartPlugins = [];
  public lineChartOptions: (ChartOptions & { annotation: any }) = {
    responsive: true,
  };
  public lineChartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: 'rgba(255,0,0,0.3)',
    },
  ];
  public lineChartData: ChartDataSets[];
  public lineChartLabels: Label[];

 ngOnInit() {
        this.http
            .get("https://api.jsonbin.io/b/5c90f7d86892a7259f084846")
            .toPromise()
            .then(response => {
                const data = response.json();
                this.summaryboardJson = data;
                console.log(this.summaryboardJson);

              //START: put data in Bar Chart
              this.lineChartData = [
                { data: this.summaryboardJson.map(a => a.noOfDefects), label: 'Defects' },
              ];
              this.lineChartLabels = this.summaryboardJson.map(a => a.Month);
              //END: put data in Bar Chart

            })
            .catch(error => {
                console.log(error);
                return Observable.of<Summaryboard[]>([]);
            });

对此有何帮助,如何使用来自 REST 调用的 JSON 来创建相同的图表?

【问题讨论】:

    标签: angular typescript ng2-charts


    【解决方案1】:

    试试这个:

    https://stackblitz.com/edit/ng2-charts-line-template-umuhe1?file=src%2Fapp%2Fapp.component.ts

    我已经更新了你的第二次堆栈闪电战

    我将 lineChartLabels 数组初始化为一个新数组,并对长度进行了 ngIf。

    【讨论】:

    • 我认为 *ngIf="lineChartLabels.length > 0" 是诀窍。我尝试了所有其他的东西。非常感谢!
    猜你喜欢
    • 2018-02-14
    • 2018-04-18
    • 2017-09-25
    • 2016-12-29
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2021-11-08
    • 2020-06-12
    相关资源
    最近更新 更多