So I'm trying to make a simple bar chart like this one (see documentation).
I'm getting my data from an observable and trying to run change detection in the subscription because the data isn't showing up in the chart, but change detection isn't doing the trick. How do I get the data to show up in the chart if it isn't loaded until after the view initializes?
Here's my code:
bar-chart.component.ts
import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { DataLoadingService } from "../data-loading.service";
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnInit {
subscription: any;
data: any;
results: any[] = [];
constructor(private dataService: DataLoadingService, private ref: ChangeDetectorRef) { }
ngOnInit(): void {
this.subscription = this.dataService.source.subscribe((val: any) => {
this.data = val.body;
for(let x = 0; x < this.data.length; x++) {
let match = false;
for(let y = 0; y < this.results.length; y++) {
if (this.results[y]["name"] === this.data[x].outcome_level) {
match = true;
this.results[y]["value"] += 1;
}
}
if(match === false) {
this.results.push({"name": this.data[x].outcome_level, "value": 1})
}
}
function compare(a: any, b: any) {
if(a.name > b.name) return 1;
if(a.name < b.name) return -1;
return 0;
}
this.results.sort(compare);
console.log(this.results);
this.ref.detectChanges();
} );
console.log("from onInit: " + this.results);
}
The output of the first console.log is as follows:
0: {name: "1", value: 3}
1: {name: "2", value: 6}
2: {name: "3", value: 1}
3: {name: "4", value: 2}
The output of console.log("from onInit: " + this.results) is empty
bar-chart.component.html
<ngx-charts-bar-vertical
[results]="results"
xAxis=true
yAxis=true
gradient=false
legend=true
showXAxisLabel=true
showYAxisLabel=true
xAxisLabel="OutcomeLevel"
yAxisLabel="NumberOfProjects"
></ngx-charts-bar-vertical>