Angular 2+等待订阅完成更新/访问变量 [英] Angular 2+ wait for subscribe to finish to update/access variable
问题描述
您好,我的变量未定义存在问题.我确定这是因为可观察的匆忙还没有完成.这是导致问题的我的.ts文件中的代码部分:(如果需要提供更多代码和上下文,我会放置理解该问题所需的最低代码.另外,myFunction
会得到通过html中的click事件调用.)
Hello I am having an issue with my variables being undefined. I am certain this is because the observable hasnt finished. Here is the part of my code in my .ts file that is causing the issue: (I'm placing the minimum code required to understand the issue, if I need to provide more code and context let me know. Also myFunction
gets called from a click event in the html.)
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
});
console.log(myVariable) --> undefined
}
}
因此,这段代码在我的服务中调用了一个函数,该函数从api返回一些数据.问题是,当我尝试在订阅函数外部访问变量myVariable
时,它返回未定义.我确定这是因为在我尝试访问myVariable
So this piece of code calls a function in my service that returns some data from an api. The issue is that when I try to access the variable myVariable
right outside of the subscribe function it returns undefined. Im sure this is because the subscribe hasnt finished before I try to access myVariable
在尝试访问myVariable
之前是否可以等待订阅完成?
Is there a way to wait for the subscribe to finish before I try to access myVariable
?
谢谢!
推荐答案
为什么不创建单独的函数并在订阅中调用它.
why not create a separate function and call it inside the subscription.
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
this.update()
});
this.update()
}
update(){
console.log(this.myVariable);
}
}
这篇关于Angular 2+等待订阅完成更新/访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!