【发布时间】:2021-05-08 19:15:13
【问题描述】:
我尝试在我的网站中显示一个包含 csv 文件数据的圆环图。但问题是,当我重新加载页面时,没有数据也没有甜甜圈,但是当我转到另一个页面(没有相同的路径)并且我回到正确的页面时,甜甜圈出现了,但我有一个错误: "ng-charts 配置错误,需要 data 或 datasets 字段才能渲染未定义的图表。"
另外,像数据每秒都在变化,如何每次刷新图表?
非常感谢,我尝试了在 google 的 4 个第一页上找到的所有内容,但没有...
HTML 代码:
<div class="doubleTrp" *ngIf="_focusedData$ | async">
<div class="trpChart">
<canvas baseChart
[chartType]="chartType"
[datasets]="chartDatasets"
[labels]="chartLabels"
[colors]="chartColors"
[options]="chartOptions"
[legend]="true"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
</div>
</div>
我的 TS 文件:
import {Component, OnInit, OnDestroy} from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label} from 'ng2-charts';
import { LineService } from '../services/line.service';
import {ActivatedRoute} from '@angular/router';
import { SingleLineComponent } from '../single-line/single-line.component';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';
@Component({
selector: 'app-trp-graph',
templateUrl: './trp-graph.component.html',
styleUrls: ['./trp-graph.component.scss']
})
export class TrpGraphComponent implements OnInit, OnDestroy{
lineSubscription: Subscription;
trpHorraire: number;
trpPoste: number;
chartType: ChartType;
chartDatasets: Array<any>
chartLabels: Array<any>;
chartColors: Array<any>;
chartOptions: any;
constructor(private lineService: LineService,
private route: ActivatedRoute) {
}
ngOnInit(): void {
this.chartIt();
}
_focusedData$ = combineLatest(
this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
this.route.params.pipe(filter(x => !!x.id), map(x => x.id -1))
).pipe(
map(([csvs, id]) => csvs[id])
);
gestionData(): void {
this.lineSubscription = this._focusedData$.subscribe(x => this.trpHorraire = x.trpHeureReel);
this.lineSubscription = this._focusedData$.subscribe(x => this.trpPoste = x.trpPosteReel);
}
async chartIt() {
await this.gestionData();
this.chartType = 'doughnut';
this.chartDatasets = [
{data: [this.trpHorraire, 100 - this.trpHorraire], label: 'TrpHorraire'}
];
this.chartLabels = ['TRP HORRAIRE'];
this.chartColors = [
{
backgroundColor: ['rgb(0, 133, 86)', 'rgb(78, 107, 124)'],
hoverBackgroundColor: ['rgb(30, 163, 116)', 'rgb(108, 137, 144)'],
borderWidth: 2,
}
];
this.chartOptions = {
responsive: true
};
}
chartClicked(e: any): void { }
chartHovered(e: any): void { }
ngOnDestroy(): void {
this.lineSubscription.unsubscribe();
}
}
因此,通过更改页面,数据会显示出来,但不会在第一次加载时显示在正确的页面上。
任何帮助都是有用的, 非常感谢。
【问题讨论】:
标签: javascript angular typescript csv charts