我有個問題。我正在嘗試用來自我的 API 的真實資料填充我的圖表。為此,我有以下 html:
<ngx-charts-bar-vertical
[results]="popularCountriesData"
[legend]="false"
[showXAxisLabel]="false"
[showYAxisLabel]="false"
[xAxis]="true"
[yAxis]="false"
[gradient]="false">
</ngx-charts-bar-vertical>
我的打字稿檔案是:
import {Component, OnInit} from '@angular/core';
import {ResearcherService} from "../../../services/researcher.service";
import {HttpErrorResponse} from "@angular/common/http";
import {PostCollection} from "../../../models/PostCollection";
@Component({
selector: 'app-dashboard-custom',
templateUrl: './dashboard-custom.component.html',
styleUrls: ['./dashboard-custom.component.css']
})
export class DashboardCustomComponent implements OnInit {
popularCountriesData: any = [];
constructor(private researcherService: ResearcherService) { this.getData(); }
private getData() {
this.researcherService.restGetStatisticsCountry().subscribe((data: PostCollection[]) => {
for (let i = 0; i < data.length; i )
this.popularCountriesData.push({ name: data[i].name, value: data[i].posts.length });
console.log(this.popularCountriesData)
},
(err: HttpErrorResponse) => {
console.log(err.error);
});
}
ngOnInit(): void {
}
}
當我運行此代碼時,我的圖表是空的,而我可以在控制臺日志中看到:
[
{
"name": "Japan",
"value": 1
},
{
"name": "Russia",
"value": 1
},
{
"name": "Netherlands",
"value": 8
}
]
如果我復制此資料并將其硬編碼在打字稿檔案中,如下所示:
popularCountriesData = [
{
"name": "Japan",
"value": 1
},
{
"name": "Russia",
"value": 1
},
{
"name": "Netherlands",
"value": 8
}
];
圖表有一個結果:

我究竟做錯了什么?
uj5u.com熱心網友回復:
this.getData();從呼叫ngOnInit。
而不是push創建新陣列并將該新陣列分配給popularCountriesData
就像是:
private getData() {
this.researcherService.restGetStatisticsCountry().subscribe((data: PostCollection[]) => {
const tempArray = [];
for (let i = 0; i < data.length; i )
tempArray.push({ name: data[i].name, value: data[i].posts.length });
this.popularCountriesData = tempArray;
console.log(this.popularCountriesData)
},
(err: HttpErrorResponse) => {
console.log(err.error);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/373485.html
標籤:javascript 有角的 打字稿
