how to initialize chart with API fetch data?

☆樱花仙子☆ 提交于 2021-02-10 07:22:55

问题


I want to use ngx-charts for my project. The problem is I don't understand how to initialize my chart with data I got from my api.

The vertical bar chart seems easy. The data is of the following type:

https://stackblitz.com/edit/vertical-bar-chart?embed=1&file=app/app.component.ts

When I assign in the constructor Object.assign(this, data) (the data I got from my api)) I receive the following error :

ERROR TypeError: Cannot read property 'toLocaleString' of undefined

Their data is the following type:

export var single = [{
    "name": "Germany",
    "value": 8940000
  },
  {
    "name": "USA",
    "value": 5000000
  },
  {
    "name": "France",
    "value": 7200000
  }
];

My data is :

[{
    "data": "2019-01-09",
    "totalConsum24": 66.66666666666667
  },
  {
    "data": "2019-02-03",
    "totalConsum24": 160
  },
  {
    "data": "2019-02-04",
    "totalConsum24": 153.84615384615384
  },
  {
    "data": "2019-02-05",
    "totalConsum24": 90.9090909090909
  }
]

Edit1: This is how i get my data from my backend. the data is the same as i posted above. In the COnstructor I begin with Object.assign(this, {single}) and initially single: any[];

ngOnInit() {
this.shipService.getConsumuriSiDataForShipById(this.shipId).subscribe(data 
=> {
  console.log(data);
  this.single = data;
});

回答1:


And in your Component, you'll have to map the data to the format that the ngx-charts understand. Here, give this a try:

...
import { ShipService } from './path-to-ship-service';

@Component({...})
export class AppComponent {

  ...,
  single = [];

  constructor(private shipService: ShipService) {}

  ngOnInit() {
    this.shipService.getConsumuriSiDataForShipById(this.shipId)
      .subscribe(data => {
        console.log(data);
        this.single = data.map(datum => ({ name: datum.data, value: datum.totalConsum24 }));
    });
  }

  ...
}

Here's a Working Sample StackBlitz for your ref.



来源:https://stackoverflow.com/questions/54605869/how-to-initialize-chart-with-api-fetch-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!