[英]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.