【问题标题】:How to load external data in Amcharts4如何在 Amcharts4 中加载外部数据
【发布时间】:2018-09-12 07:44:38
【问题描述】:

我目前正在试用 amCharts 4,并希望将我的 json 加载到图表中。因为我的 json 是嵌套的,所以我添加了一个 on parseended 事件来更改我的 json 结构。当我控制台记录新数据时,它具有正确的结构。但是当我想将它加载到类别中时,它什么也不显示。目前我只希望类别显示没有额外的值。

我的组件.ts

import { Component, NgZone } from '@angular/core';
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";

am4core.useTheme(am4themes_animated);

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})

export class ChartComponent {
  constructor(private zone: NgZone) { }

  ngAfterViewInit() {
    this.zone.runOutsideAngular(() => {
      let chart = am4core.create("chartdiv", am4charts.XYChart)

      chart.paddingRight = 30;
      chart.dateFormatter.inputDateFormat = "yyyy-MM-dd HH:mm";

      var colorSet = new am4core.ColorSet();
      colorSet.saturation = 0.4;
      chart.dataSource.url = "https://localhost:44321/api/upload/readFile";
      chart.dataSource.events.on("parseended", function (ev) {
        // parsed data is assigned to data source's `data` property
        var data = ev.target.data;
        var newData = [];
        data.forEach(function (dataItem) {
          var newDataItem = {};
          Object.keys(dataItem).forEach(function (key) {
            if (typeof dataItem[key] === "object") {
              newDataItem["_id"] = dataItem[key]["@id"];
            } else {
              newDataItem[key] = dataItem[key];
            }
          });
          newData.push(newDataItem);         
        });
        console.log(JSON.stringify(newData));
        return newData
      });

      var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
      categoryAxis.dataFields.category = "_id";
      categoryAxis.renderer.grid.template.location = 0;
      categoryAxis.renderer.inversed = true;


      var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
      dateAxis.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm";
      dateAxis.renderer.minGridDistance = 70;
      dateAxis.baseInterval = { count: 30, timeUnit: "minute" };
      dateAxis.max = new Date(2018, 0, 1, 24, 0, 0, 0).getTime();
      dateAxis.strictMinMax = true;
      dateAxis.renderer.tooltipLocation = 0;

      var series1 = chart.series.push(new am4charts.ColumnSeries());
      series1.columns.template.width = am4core.percent(80);
      series1.columns.template.tooltipText = "{name}: {openDateX} - {dateX}";

      series1.dataFields.openDateX = "fromDate";
      series1.dataFields.dateX = "toDate";
      series1.dataFields.categoryY = "name";
      series1.columns.template.propertyFields.fill = "color"; // get color from data
      series1.columns.template.propertyFields.stroke = "color";
      series1.columns.template.strokeOpacity = 1;

      chart.scrollbarX = new am4core.Scrollbar();

      chart.dataSource.events.on("error", function (ev) {
        console.log("Oopsy! Something went wrong");
      });
    })
  }
}

【问题讨论】:

    标签: angular typescript amcharts


    【解决方案1】:

    使用chart.dataSource.url 加载外部数据的想法是正确的。

    要解析外部 JSON 并对其进行格式化,使其适用于 chartseries 或类别轴 data,最好使用适配器。适配器允许您根据自己的喜好调整事物。我们在这里有一个指南:https://www.amcharts.com/docs/v4/concepts/adapters/

    在这种情况下,一旦解析了 JSON,就可以使用 parsedData 的适配器。代码如下所示(取自 another question of yours 并已修复):

    chart.dataSource.adapter.add("parsedData", function(data) {
      var newData = [];
      data.forEach(function(dataItem) {
        var newDataItem = {};
        Object.keys(dataItem).forEach(function(key) {
          if (typeof dataItem[key] === "object") {
            newDataItem["_id"] = dataItem[key]["@id"];
            dataItem[key]["Column"].forEach(function(dataItem) {
              newDataItem[dataItem["@name"]] = dataItem["@id"];
            });
          } else {
            newDataItem[key] = dataItem[key];
          }
        });
        newData.push(newDataItem);
      });
      data = newData;
      return data;
    });
    

    这是一个演示(还从您的其他问题中获取示例 JSON,修复了 JSON 和格式化逻辑):

    https://codesandbox.io/s/r1mnjq192p

    【讨论】:

      【解决方案2】:

      我通过添加以下行来修复它: 替换这个: return newData 用这个: chart.dataSource.data = newData

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-27
        • 2020-01-01
        相关资源
        最近更新 更多