I've hit a roadblock and can't seem to figure it out. Despite scouring the forum and tirelessly searching on Google for hours, I'm unable to solve this issue! This is my first attempt at creating an app with Angular, and it's safe to say that I am struggling.
The problem lies with a class variable called stats4Graphs
which I receive from a service in .net core 3.1. While I can successfully display the data in the html section of the component using
stats4Graph<code>, I encounter difficulties when trying to utilize the variable within the function that calls the service. Even a simple statement like <code>console.log('Labels in: ' + this.stats4Graphs.label);
returns "Labels in: undefined" in the console. I'm completely stuck and don't know how to proceed.
Here is the model definition for stats4Graphs:
export class Stats4Graphs {
axisLabels: string[] = [];
label: string;
points: number[] = [];
}
I'm unsure if I need to initialize the arrays here or not; it was one of my last-ditch efforts to resolve the issue.
Below is the code snippet from my component.ts file:
import { Component, OnInit } from '@angular/core';
import { Stats4Graphs } from 'src/app/shared/models/stats4-graphs.model';
import { ProfileService } from '../profile.service';
@Component({
selector: 'app-engagement-chart',
templateUrl: './engagement-chart.component.html',
styleUrls: ['./engagement-chart.component.css']
})
export class EngagementChartComponent implements OnInit {
public stats4Graphs: Stats4Graphs = new Stats4Graphs();
// ADD CHART OPTIONS.
chartOptions = {
responsive: true // THIS WILL MAKE THE CHART RESPONSIVE (VISIBLE IN ANY DEVICE).
}
labels = [];
// STATIC DATA FOR THE CHART IN JSON FORMAT.
chartData = [
{
label: '',
data: []
}
];
// CHART COLOR.
colors = [
{ // 1st Year.
backgroundColor: 'rgba(77,83,96,0)',
borderColor: 'rgba(77,83,96,0.2)',
borderWidth : 2
}
]
// CHART CLICK EVENT.
onChartClick(event) {
console.log(event);
}
constructor(private profileService: ProfileService) { }
ngOnInit() {
this.profileService.getEngagement('UC__8h96Jwsaptaqh227Q9gg')
.subscribe(stats4Graphs => {
this.stats4Graphs = stats4Graphs;
});
console.log('Labels in engagement: ' + this.stats4Graphs.label);
this.labels = this.stats4Graphs.axisLabels as any;
}
}
In essence, I am attempting to create a line chart using Chart.js and ng2-charts to showcase the data within stats4Graphs
. However, I'm clueless about how to populate chartData
with the information from stats4Graphs.points
and stats4Graphs.label
. Any guidance regarding this would be greatly appreciated.
Despite my struggle, I can confirm that the service does work because I'm able to display the values retrieved from the service in the component.html file.
<p>{{ stats4Graphs.label }}
<br />
{{ stats4Graphs.axisLabels }}
<br />
{{ stats4Graphs.points }}
</p>
Thank you for your anticipated assistance!