【发布时间】:2018-11-29 19:08:01
【问题描述】:
您好,我的变量未定义有问题。我确信这是因为可观察的还没有完成。这是我的 .ts 文件中导致问题的代码部分:(我放置了理解问题所需的最少代码,如果我需要提供更多代码和上下文,请告诉我。还有myFunction 获取从 html 中的点击事件调用。)
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
});
console.log(myVariable) --> undefined
}
}
因此,这段代码在我的服务中调用了一个函数,该函数从 api 返回一些数据。问题是当我尝试在订阅函数之外访问变量myVariable 时,它返回未定义。我确定这是因为在我尝试访问myVariable之前订阅还没有完成
在我尝试访问myVariable之前,有没有办法等待订阅完成?
谢谢!
【问题讨论】:
标签: angular observable subscribe