Angular 6等待订阅完成 [英] Angular 6 wait for subscribe to finish

查看:73
本文介绍了Angular 6等待订阅完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的功能

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 是从其他函数获取的.问题是 this.newVariable 为空.我确定这是因为在尝试访问 this.Variable

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?

推荐答案

只需从getNumber返回一个Observable并订阅它即可.

Just return an Observable from getNumber and subscribe to it.

您还可以将管道添加到getNumber,以便它将处理存储数据并返回Observable进行订阅.

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;
    }));
}

在您设置的方法中

set() {
    if (this.value == 1) {
      this.getNumber(firstNumber).subscribe(() => {
        this.newVariable = this.myVariable;
      });
    }
    else {
      this.getNumber(secondNumber).subscribe(() => {
        this.newVariabe = this.myVariable + 1;
      });
   }
};

这篇关于Angular 6等待订阅完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆