Got a question about chartjs in an angular11 environment.
I have 2 charts
appcomponent.html:
<div class="col-sm">
<canvas id="bl" ></canvas>
</div>
<div class="col-sm">
<canvas id="bl2" ></canvas>
</div>
app.component.ts:
export class AppComponent {
testChart: any;
testChart2: any;
...
constructor(private dataSvc:DataRetrieverService){
dataSvc.getUsers.subscribe( data=> {
if(!data) return;
this.Users = data;
this.Users.forEach(x => {
this.UsersLabels.push(x.StoreDateTime);
this.UsersAmount.push(x.Amount);
this.CreateCharts();
})
})
dataSvc.getParts.subscribe( data=> {
if(!data) return;
this.Parts = data;
this.Parts.forEach(x => {
this.PartsLabels.push(x.StoreDateTime);
this.PartsAmount.push(x.Amount);
this.CreateCharts();
})
})
}
CreateCharts(){
if(this.testChart){
this.testChart.destroy()
}
if(this.testChart2){
this.testChart2.destroy()
}
this.testChart = new Chart('bl', {
type: 'line',
data: {
labels: this.UsersLabels,
datasets: [
{
label: 'Users',
data: this.UsersAmount,
borderColor: '#01c38c',
backgroundColor: '#01c38c',
fill: false
}
]
},
options: {... }
}
});
this.testChart2 = new Chart('bl2', {
type: 'line',
data: {
labels: this.PartsLabels,
datasets: [
{
label: 'Parts',
data: this.PartsAmount,
borderColor: '#01c38c',
backgroundColor: '#01c38c',
fill: true
}
]
},
options: {...
}
});
Is creating the testChart: Any the correct thing to do?
Why do I have to call this.CreateCharts() after every data retrieval from the service in order to make it work?
I would expect if I would do a this.CreateCharts() at the very last step of the constructor it would also work, but then my chart is empty.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…