I am utilizing Charts.js in my Angular project (not AngularJS) and I am trying to create a graphic representation with data from my database that shows the distribution between men and women. However, I am struggling to figure out how to loop through the data to count the number of men and women:
Firstly, for the Chart, here is my HTML code :
<canvas id="myChart" width="700" height="400"></canvas>
Typescript code :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Female", "Male"],
datasets: [{
label: '# of Votes',
data: [2, 2],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}
and the code to fetch my data :
Javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
}
});
})
Typescript :
GetUser(){
return this.http.get('http://localhost:8080/api/getUser/')
.map((response: Response) => response.json())
}
and another piece of Typescript :
ngOnInit() {
this.newService.GetUser().subscribe(data => this.Repdata = data)
}
Finally, here is an example entry from the collection :
{
"_id" : ObjectId("5b9551a60e89ad15a8ff77fb"),
"name" : "XXX",
"prenom" : "KEVIN",
"datenaissance" : "17/11/2011",
"mail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a010f1c03040a262b3a25393e2f642c38">[email protected]</a>",
"tel" : "XXXXXXXXXX",
"sexe" : "Male",
"adresse" : "XXXXXXXX",
"note" : [
{
"matiere" : "French",
"note" : "10/20",
"date" : "01/09/2018"
},
{
"subject" : "English",
"grade" : "07/20",
"date" : "26/09/2018"
},
{
"subject" : "Physical Education",
"grade" : "15/20",
"date" : "29/09/2018"
}
]
}
I am looking to count the number of males and females present in the dataset so that I can represent it on my chart but I am unsure about the process.
Thank you for your help.
If I attempt to do this, my charts cannot find the variables countHomme and countFemme :
Javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
var countHomme = model.where({ 'sexe': 'Male' }).count();
res.send(countHomme);
var countFemme = model.where({ 'sexe': 'Female' }).count();
res.send(countFemme);
}
});
})
Typescript :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Female", "Male"],
datasets: [{
label: '# of Votes',
data: [countFemme, countHomme],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}