angular - 订阅方法返回未定义
问题描述
get() {
const obs = this.http.get(this.url);
obs.subscribe((response) => {this.sakla = response;
});
constructor(private geolocation: Geolocation,public http: HttpClient) {
}
ngOnInit() {
this.get();
console.log(this.sakla); //x line
}
get() 函数在 ngOnInit() 之后完成。所以 x 行给出 undefined 因为在 ngoninit 中没有完全执行 this.get() 函数。我该怎么办?
解决方案
让我在步骤中标记它以澄清您的查询:
get(){
// step 3
const obs = this.http.get(this.url);
obs.subscribe((response) => {
// stpe 5
this.sakla = response;
});
constructor(private geolocation: Geolocation,public http: HttpClient) { // step 1 }
ngOnInit(){
// step 2
this.get();
// step 4
console.log(this.sakla); //x line
}
未定义的原因是“http.get()”本质上是异步的,也就是说,在您收到响应之前,您的代码将已经执行“console.log()”,因此,您将获得未定义。
为了纠正同样的问题,可以做以下事情:
a) 从 get 方法返回 observable 并在 ngOnit 方法中订阅
b) 在 get 方法定义以及 this.get() 调用中使用 async-await
c) 将其转换为承诺并在收到响应时解决承诺。
d)简单地说,只登录订阅方法
干杯(y)
推荐阅读
- ignite - 如何将数据均匀分布到 apache ignite 集群中并在其中进行计算
- python-2.7 - 运行烧瓶时出错:TypeError: get() 恰好需要 2 个参数(给定 1 个)
- sql - 甲骨文。重命名名为“count”的列
- verilog - d[7:0] 是输入向量,在仿真波形中显示为 ZZ。Xilinx Vivado 仿真中何时会出现这种情况?
- npm - NPM 与 WEBPACK 比较
- python - 在 python 3.4.7 的 pool.map 函数中添加额外的随机参数作为参数
- python - 如果我没有说什么,语音识别就会停止,如何让它一直在听
- odoo - 需要为除 ir.sequence 之外的一个 sale.order 打印五个序列号
- python - 在 python ex25.py 中得到不同的输出。来自Learn python the hardway.python 3.6
- c# - 特殊字符给使用 C# 解析 xml 带来问题