【问题标题】:Angular Ngx Charts chart stays emptyAngular Ngx Charts 图表保持空白
【发布时间】:2021-12-05 20:24:00
【问题描述】:

我有问题。我正在尝试用我的 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
    }
]

如果我复制这些数据并将其硬编码到 typescript 文件中,如下所示:

popularCountriesData = [
        {
            "name": "Japan",
            "value": 1
        },
        {
            "name": "Russia",
            "value": 1
        },
        {
            "name": "Netherlands",
            "value": 8
        }
];

图表有一个结果:

我做错了什么?

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    ngOnInit 致电this.getData();

    而不是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);
                });
        }
    

    【讨论】:

    • 所以我不允许push到真实数组?
    • 您可以这样做,但更改检测将无法识别它。这就是为什么你需要一个新的数组实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多