I have the following chart, which I want to use data that I have stored in some methods, the code for context:
...
charts: any
...
constructor(
private measureService: MeasureService,
) { }
...
ngOnInit() {
this.getPublished()
this.getEdits()
this.chart = new Chart('canvas', {
type: "doughnut",
data: {
labels: ["Test 1", "Test 2"],
datasets: [
{
data: [this.numberEditing, this.numberPublished], // <- DATA GOES HERE
backgroundColor: ['rgba(255, 0, 0, 1)', 'rgba(13, 180, 185, 1)']
}
],
},
})
}
I stored the data (number) from this.numberEditing and this.numberPublished
in the following methods:
getPublishedNumber(numberPublished) {
this.numberPublished = numberPublished
}
getNumberEditing(numberEditing) {
this.numberEditing = numberEditing
}
The data is there after the following subscribe happens:
getEdits() {
this.measureService.getEditing().subscribe(data => this.getNumberEditing(data.length))
}
getPublished() {
this.measureService.getPublished().subscribe(data => this.getPublishedNumber(data.length))
}
I have reached the conclusion of storing the data there for usage later after reading a few similar things here on Stackoverflow, however
I have no clue how I am going to use those numbers stored inside the methods, on my chart, how would that even happen?
I am trying to figure out Angular still, been on it for only a week and jesus.
CodePudding user response:
That is why we have the rxjs operators which can perform intermediate operations inbetween the subscribe and the calls.
...
charts: any
...
constructor(
private measureService: MeasureService,
) { }
...
ngOnInit() {
forkJoin([
this.getPublished(),
this.getEdits(),
]).subscribe(() => {
this.chart = new Chart('canvas', {
type: "doughnut",
data: {
labels: ["Test 1", "Test 2"],
datasets: [
{
data: [this.numberEditing, this.numberPublished], // <- DATA GOES HERE
backgroundColor: ['rgba(255, 0, 0, 1)', 'rgba(13, 180, 185, 1)']
}
],
},
})
});
}
Then the methods can be modified to return an observable with a pipe operator, followed by a tap, which can perform operations without modifying the stream
getEdits() {
return this.measureService.getEditing().pipe(
tap(data => this.getNumberEditing(data.length))
);
}
getPublished() {
return this.measureService.getPublished().pipe(
tap(data => this.getPublishedNumber(data.length))
);
}
CodePudding user response:
You should use async - await functionality for API response. When you get response from API then you can pass this two data in Chart.
you have to pass data in doughnut or Pie chart of chartjs like below:
import { Chart } from 'chart.js';
this.chart = new Chart('canvas', {
type: 'doughnut',
data: {
datasets: [
{
data: this.numberEditing, // Alwasy number type of List. number[]
backgroundColor: 'rgba(255, 0, 0, 1)',
},
{
data: this.numberPublished, // Alwasy number type of List. number[]
backgroundColor: 'rgba(13, 180, 185, 1)'
}
]
},
});