首页 > 解决方案 > 订阅方法返回未定义

问题描述

 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() 函数。我该怎么办?

标签: angulartypescriptapiionic-framework

解决方案


让我在步骤中标记它以澄清您的查询:

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)


推荐阅读