2

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;
});
gxg
  • 110
  • 2
  • 15
  • Your example works for me, could you please provide an example when it fails, because it's difficult to understand as is. (If you want to simulate backend calls, you can use of(data) to get an observable similar as from HttpClient) – Amir Arbabian Feb 09 '19 at 11:52
  • I added an edit with more details about my backend call – gxg Feb 09 '19 at 12:07

1 Answers1

2

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.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • My data that i fetch from my backend is very similar to single, why should i use multi ? I added an edit to provide more details – gxg Feb 09 '19 at 12:08
  • Yes, it works now. These things need to be in the documentations ! :) Kind regards ! – gxg Feb 09 '19 at 13:35
  • 1
    There actually is a section named **[Data Format](https://swimlane.gitbook.io/ngx-charts/examples/bar-charts/vertical-bar-chart#data-format)** in the documentation. But yeah I agree that it must be explicitly mentioned that the data needs to be in the exact same format. – SiddAjmera Feb 09 '19 at 13:38