使用ngx图表并从可观察到的数据加载



所以我正在尝试制作一个像这样的简单条形图(请参阅文档(。

我从一个可观察的数据中获取数据,并试图在订阅中运行更改检测,因为数据没有显示在图表中,但更改检测并没有起到作用。如果直到视图初始化后才加载数据,如何使数据显示在图表中?

这是我的代码:

条形图组件.ts

import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { DataLoadingService } from "../data-loading.service";
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnInit {
subscription: any;
data: any;
results: any[] = [];
constructor(private dataService: DataLoadingService, private ref: ChangeDetectorRef) { }
ngOnInit(): void {
this.subscription = this.dataService.source.subscribe((val: any) => {
this.data = val.body;
for(let x = 0; x < this.data.length; x++) {
let match = false;
for(let y = 0; y < this.results.length; y++) {
if (this.results[y]["name"] === this.data[x].outcome_level) {
match = true;
this.results[y]["value"] += 1;
}
}
if(match === false) {
this.results.push({"name": this.data[x].outcome_level, "value": 1})
}
}
function compare(a: any, b: any) {
if(a.name > b.name) return 1;
if(a.name < b.name) return -1;
return 0;
}
this.results.sort(compare);
console.log(this.results);
this.ref.detectChanges();
} );
console.log("from onInit: " + this.results);
}

第一个console.log的输出如下:

0: {name: "1", value: 3}
1: {name: "2", value: 6}
2: {name: "3", value: 1}
3: {name: "4", value: 2}

console.log("from onInit:"+this.results(的输出为空

条形图.component.html

<ngx-charts-bar-vertical
[results]="results"
xAxis=true
yAxis=true
gradient=false
legend=true
showXAxisLabel=true
showYAxisLabel=true
xAxisLabel="OutcomeLevel"
yAxisLabel="NumberOfProjects"
></ngx-charts-bar-vertical>

你好,我遇到了和你一样的问题,我设法找到了一个解决方法:

  • 1-在条形图.component.ts中添加一个新变量(例如:dataReceived=false(
  • 2-在订阅方法的处将dataReceived的值更改为true
  • 3-然后条形图.component.html使用*ngif(dataReceived(来呈现图表

在订阅方法中,更改检测似乎不起作用(附言:这只是我的结论,我是Angular的新手^^(

最新更新