I'm using Angular 6
.
In my component.ts file, I have to initialize graph and doing so in ngOnIt() method like this
@Component({
selector: 'app-contact-detail',
templateUrl: './contact-detail.component.html',
styleUrls: ['./contact-detail.component.css']
})
export class ContactDetailComponent implements OnInit {
contact_id: string;
public graph_data_year;
constructor(
private activatedRoute: ActivatedRoute,
private graphDataService: GraphDataService
) { }
ngOnInit() {
this.activatedRoute.params.subscribe(
param => {
this.contact_id = param['id'];
}
);
/**
* Get Amount Given Graph Data
*/
this.graphDataService.get_data(this.contact_id).subscribe(
res => {
const data = [];
res.forEach(e => {
data.push(e.total);
});
this.graph_data_year = data;
this._setGraphData();
}
);
this.initializeGraph();
}
_setGraphData() {
this.lineBigDashboardChartData[0]['data'] = this.graph_data_year;
// this console here gives updated value in the console window, but no update on chart
console.log(this.lineBigDashboardChartData);
}
/**
* Graph
*/
initializeGraph() {
...
this.lineBigDashboardChartData = [
{
label: 'Data',
...
...
data: this.graph_data_year
}
];
this.lineBigDashboardChartLabels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
this.lineBigDashboardChartType = 'line';
}
}
and component.html is like
<canvas baseChart id="bigDashboardChart"
[datasets]="lineBigDashboardChartData"
[labels]="lineBigDashboardChartLabels"
[chartType]="lineBigDashboardChartType"></canvas>
But it does not update the chart with the updated value of graph_data_year which is updated by this.graphDataService. and shows the blank chart.
console.log(this.lineBigDashboardChartData);
after updating data prints updated values in console window but chart data is not update.
How can I have an async variable inside component which on the update, updates value in every place it has been used in the component? Or how can I refresh the cart after updating the data?
Extended @Mehmet answer and this fixed my issue.
this.lineBigDashboardChartLabels.length = 0;
this.lineBigDashboardChartLabels.push(...label_data);