angular - 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;
});
感谢是否有人可以帮助我。
解决方案
Observables
are 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();
}
推荐阅读
- java - 如何通过 id 获取其他用户信息(用户名、名字)?[钥匙斗篷]
- sql - 使用追加模型在 BigQuery 中进行部分行更新
- java - 为什么 netty FastThreadLocal public final V get(InternalThreadLocalMap threadLocalMap) 不调用 registerCleaner 方法?
- android - 如何在 android 中使用开放街道地图包含 GeoJson?
- python - Pandas - 检查其他列是否有基于不同列的重复项
- mysql - 在字符串表mysql语句中查找数字
- python - 是否有可能为 Fiddler 或 mitmdump 中的每个请求动态更改 IP?
- c++ - 在“consoleHandler”功能从用户获取 Ctrl-C 后无法立即获取下一个用户命令
- dart - 如何从 B-BLoC 函数调用 A-BLoC 函数?
- python - Jupyter Notebook 中的 Savefig 失败:“用户警告:此图是使用 matplotlib 版本 2.0.0 保存的,不太可能正常运行。”