Angular 6 wait for subscribe to finish

落花浮王杯 提交于 2021-01-03 07:32:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!