[英]Angular 6 wait for subscribe to finish
我有这样的功能:
getNumber(value) {
this.myService.getApi(value).subscribe(data => {
this.myVariable = data;
});
}
我在其他函数中调用该函数如下:
set() {
if (this.value == 1) {
this.getNumber(firstNumber)
this.newVariable = this.myVariable;
} else {
this.getNumber(secondNumber)
this.newVariabe = this.myVariable + 1;
}
};
this.value
是从其他函数中获取的。 问题是this.newVariable
是空的。 我确定这是因为在我尝试访问this.Variable
之前订阅还没有完成
在我做其他任何事情之前,有没有办法等待订阅完成?
只需从 getNumber 返回一个 Observable 并订阅它。
您还可以向 getNumber 添加管道,以便它处理存储数据并返回一个 Observable 以供订阅。
getNumber(value) {
return this.myService.getApi(value).pipe(tap(data => {
this.myVariable = data;
}));
}
在你的 set 方法中
set() {
if (this.value == 1) {
this.getNumber(firstNumber).subscribe(() => {
this.newVariable = this.myVariable;
});
}
else {
this.getNumber(secondNumber).subscribe(() => {
this.newVariabe = this.myVariable + 1;
});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.