如何通过订阅返回值?

问题描述:

如何通过订阅返回值?如何通过订阅返回值?

我试图创建一个全局变量,但我没有成功。

this.postServices.getData().subscribe((res)=>{ 
       this.data = res 
      }) 

console.log(this.data) 

第一部分启动异步操作,并且console.log部分被立即运行,异步操作完成之前。

您必须延迟引用this.data,直到您知道异步操作已完成。

你可以做到这一点通过将console.log的订阅处理程序中:

this.postServices.getData().subscribe((res)=>{ 
    this.data = res; 
    console.log(this.data); 
})