首页 > 解决方案 > Angular .subscribe 在 ngOnInit 之后最后执行

问题描述

我是角度的新手。我正在尝试下面的代码来填充饼图。我在构造函数中分配值。但是这里 .subscribe 方法在 ngOnInit() 执行后最后执行。它显示 undefined 作为 this.TestVar 的值

cities: Observable<DataModel>;
TestVar: string;

constructor(private http: HttpClient) {

this.cities = this.http.get<DataModel>('./assets/data.json');

    this.cities.subscribe(events => {
      this.TestVar = events[0].District;
    });
}
ngOnInit() {
    let chart = new CanvasJS.Chart("chartContainer", {
        theme: "light2",
        animationEnabled: true,
        exportEnabled: true,
        title:{
            text: "Monthly Expense"
        },
        data: [{
            type: "pie",
            showInLegend: true,
            toolTipContent: "<b>{name}</b>: ${y} (#percent%)",
            indexLabel: "{name} - #percent%",
            dataPoints: [
                { y: 450, name: this.TestVar },
                { y: 120, name: "Insurance" },
                { y: 300, name: "Traveling" },
                { y: 800, name: "Housing" },
                { y: 150, name: "Education" },
                { y: 150, name: "Shopping"},
                { y: 250, name: "Others" }
            ]
        }]
    });

    chart.render();
}

我什至尝试在 ngOnInit() 中添加以下代码。但这并没有解决我的问题。

this.cities.subscribe(events => {
      this.TestVar = events[0].District;
});

感谢是否有人可以帮助我。

标签: angulartypescriptchart.js

解决方案


Observablesare async,这意味着您正在尝试this.TestVar在 http 请求完成之前使用 的值,因此仍未定义。

如果在 observable 完成后初始化图表,则可以保持同步:

 cities: Observable<DataModel>;
    TestVar: string;

    constructor(private http: HttpClient) {
        this.cities.subscribe(events => {
          this.TestVar = events[0].District;
          this.init();
        });
    }

    ngOnInit() {
       this.cities = this.http.get<DataModel>('./assets/data.json');
    }

public init(): void {
let chart = new CanvasJS.Chart("chartContainer", {
            theme: "light2",
            animationEnabled: true,
            exportEnabled: true,
            title:{
                text: "Monthly Expense"
            },
            data: [{
                type: "pie",
                showInLegend: true,
                toolTipContent: "<b>{name}</b>: ${y} (#percent%)",
                indexLabel: "{name} - #percent%",
                dataPoints: [
                    { y: 450, name: this.TestVar },
                    { y: 120, name: "Insurance" },
                    { y: 300, name: "Traveling" },
                    { y: 800, name: "Housing" },
                    { y: 150, name: "Education" },
                    { y: 150, name: "Shopping"},
                    { y: 250, name: "Others" }
                ]
            }]
        });

        chart.render();
}

推荐阅读