我正在angular中做一个项目,我正在使用angular 11。
我的问题是ng2图表。简而言之,对后端进行api请求调用,用数据填充图表。
我想我知道问题出在哪里,但不知道该怎么解决:
模板(因此图表(是在没有任何数据的情况下初始化的。因此,当调用api加载数据时,模板已经存在,这使得图表本身为空。当我刷新数据时,数据已经存在,并且数据按预期加载。
正如你所看到的,
export class ChartComponent implements OnInit, OnDestroy {
public doughnutChartLabels: Label[] = [];
public doughnutChartData: MultiDataSet = [
[]
];
public doughutColors: any[] = [];
public pieChartColors: Array <any> = [{
backgroundColor: []
}];
public doughnutChartType: ChartType = 'doughnut';
private subscriptions: Subscription[] = [];
public loaded: boolean = false;
constructor(private pLanguageService: PLanguageService,
private analyticsService: AnalyticsService,
private subscriptionService: SubscriptionService,
public changeDetector: ChangeDetectorRef) {}
ngOnDestroy(): void {
this.subscriptionService.unsubscribeParam(this.subscriptions);
}
ngOnInit(): void {
this.initData();
}
private initData(): void {
const subscription: Subscription = this.pLanguageService
.findAll()
.pipe(switchMap((pLanguage: Planguage[]) => {
return this.analyticsService.getUsageStatisticsOfPLanguages();
}))
.subscribe((data: UsageStatistics) => {
this.initChart(data);
});
this.subscriptions.push(subscription);
}
private initChart(statistics: UsageStatistics): void {
this.initUsagePercentages(statistics);
this.visualizeChart();
console.log("initialization done");
}
private visualizeChart(): void {
this.pieChartColors = [{backgroundColor: this.doughutColors}];
this.loaded = true;
}
private initUsagePercentages(statistics: UsageStatistics): void {
for(let i = 0; i < statistics.planguages.length; i++) {
this.doughnutChartLabels.push(statistics.planguages[i].language);
this.doughnutChartData[0].push(statistics.numberSubmissions[i]);
this.doughutColors.push(`${statistics.planguages[i].color}`);
}
}
}
这是我的组件模板
<ng-container *ngIf="loaded">
<div id="chart">
<div class="card shadow mb-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h4 style="margin-bottom: 4px;margin-top: 4px;">Language use distribution</h4>
</div>
<div class="card-body">
<div class="chart-area">
<div style="display: block;">
<canvas baseChart
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[chartType]="doughnutChartType"
[colors]="pieChartColors">
</canvas>
</div>
</div>
</div>
</div>
</div>
</ng-container>
所以我现在正在尝试的是防止模板";从装载";在数据可用之前,但这不起作用。
我的目标是在不刷新整个窗口的情况下更新图表(或刷新组件(。有什么帮助吗?
您操作同一个对象,这就是为什么angular不再次更新组件的原因。
this.doughnutChartData[0].push(statistics.numberSubmissions[i]);
这里的简单技巧是将对象分配给新的引用:
for(let i = 0; i < statistics.planguages.length; i++) {
this.doughnutChartLabels.push(statistics.planguages[i].language);
this.doughnutChartData[0].push(statistics.numberSubmissions[i]);
this.doughutColors.push(`${statistics.planguages[i].color}`);
}
至:
for(let i = 0; i < statistics.planguages.length; i++) {
...
}
this.doughnutChartLabels = [...this.doughnutChartLabels];
this.doughnutChartData= [...this.doughnutChartData];
在推送甜甜圈图表数据后,请尝试使用this.chartchart.update((。