0

When I push an array to ngx-barchart, the push function adds an empty object to the chart. I loop through the api service and get this:

enter image description here

Then I call the service in barchart.component.ts

  single: any = [
    {
      "name": [],
      "value": []
    }      
  ];

function to push:

getChartData() { 
    this.storageService.barChart.subscribe(barChart=> {if(barChart) 
        barChart.forEach((i) => {         
          // this.single[0].push({name: (i.skill_name), value: (i.score)})          
          this.single.push({name: (i.skill_name), value: (i.score)});
      });
      this.single=[...this.single];
      console.log(this.single)
    });      
  };

I'm expecting the to not have an empty object passed to my chart data. empty object

I've tried adding:

this.single[0].push({name: (i.skill_name), value: (i.score)})

But I get ERROR TypeError: _this.single[0].push is not a function

Seeker C
  • 67
  • 9

2 Answers2

0

I'm expecting the to not have an empty object passed to my chart data.

Then don't create one at the outset, that's the blank one you have in your data.

Instead of:

single: any = [
  {
    "name": [],
    "value": []
  }      
];

just:

single: any = [];

Side Note 1: I wouldn't use push here at all unless you want to keep adding more and more data to this.single. If you mean to replace this.single each time, I'd use map:

this.single = (barChart || []).map(({skill: {score: value, name}}) => ({name, value}));
// (And no `this.single = [...this.single];` afterward, it's not needed)

Side Note 2: Since this is TypeScript, you might benefit from a type for this data:

interface ChartDataEntry {
    name: string;
    value: number; // If it's a number
}

then

single: ChartDataEntry[] = [];

the this.single = ... line doesn't change, TypeScript can infer the type of entries being returned by map and can see that they're valid for that interface.

Or if you prefer, instead of declaring an interface you can just declare the type of entries inline with single:

let single: {name: string, value: number}[] = [];

but having a declared type is usually useful because you may find you want to use it elsewhere in the same code.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

this.single[0] is object not array

You can try:

this.single[0].name = i.skill_name;
this.single[0].value= i.score;