问题
I have function like:
getNumber(value) {
this.myService.getApi(value).subscribe(data => {
this.myVariable = data;
});
}
And I am calling that function in other function as follows :
set() {
if (this.value == 1) {
this.getNumber(firstNumber)
this.newVariable = this.myVariable;
} else {
this.getNumber(secondNumber)
this.newVariabe = this.myVariable + 1;
}
};
this.value
is getting from other function. The problem is that this.newVariable
is empty. I'm sure this is because the subscribe hasn't finished before I try to access this.Variable
Is there any way to wait for the subscribe to finish before I do anything else?
回答1:
Just return an Observable from getNumber and subscribe to it.
You can also add pipe to getNumber so it will handle storing data and also return an Observable to subscribe to.
getNumber(value) {
return this.myService.getApi(value).pipe(tap(data => {
this.myVariable = data;
}));
}
And in your set method
set() {
if (this.value == 1) {
this.getNumber(firstNumber).subscribe(() => {
this.newVariable = this.myVariable;
});
}
else {
this.getNumber(secondNumber).subscribe(() => {
this.newVariabe = this.myVariable + 1;
});
}
};
来源:https://stackoverflow.com/questions/54888671/angular-6-wait-for-subscribe-to-finish