I am new to angular. I am trying the below code to populate a pie chart. I am assigning the values inside the constructor. But here the method .subscribe executes at the end after the ngOnInit() executes. And it displays undefined as the value of this.TestVar
cities: Observable<DataModel>;
TestVar: string;
constructor(private http: HttpClient) {
this.cities = this.http.get<DataModel>('./assets/data.json');
this.cities.subscribe(events => {
this.TestVar = events[0].District;
});
}
ngOnInit() {
let chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
animationEnabled: true,
exportEnabled: true,
title:{
text: "Monthly Expense"
},
data: [{
type: "pie",
showInLegend: true,
toolTipContent: "<b>{name}</b>: ${y} (#percent%)",
indexLabel: "{name} - #percent%",
dataPoints: [
{ y: 450, name: this.TestVar },
{ y: 120, name: "Insurance" },
{ y: 300, name: "Traveling" },
{ y: 800, name: "Housing" },
{ y: 150, name: "Education" },
{ y: 150, name: "Shopping"},
{ y: 250, name: "Others" }
]
}]
});
chart.render();
}
I tried adding the below code inside ngOnInit() even. But it didnt fix my issue.
this.cities.subscribe(events => {
this.TestVar = events[0].District;
});
Appreciate if anyone can help me with this.