Angular 2+等待订阅完成更新/访问变量 [英] Angular 2+ wait for subscribe to finish to update/access variable

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

问题描述

您好,我的变量未定义存在问题.我确定这是因为可观察的匆忙还没有完成.这是导致问题的我的.ts文件中的代码部分:(如果需要提供更多代码和上下文,我会放置理解该问题所需的最低代码.另外,myFunction会得到通过html中的click事件调用.)

Hello I am having an issue with my variables being undefined. I am certain this is because the observable hasnt finished. Here is the part of my code in my .ts file that is causing the issue: (I'm placing the minimum code required to understand the issue, if I need to provide more code and context let me know. Also myFunction gets called from a click event in the html.)

export class myClass {
  myVariable: any;

  myFunction() {
    this.myService.getApi().subscribe(data => {
      this.myVariable = data;
    });

    console.log(myVariable) --> undefined
  }
}

因此,这段代码在我的服务中调用了一个函数,该函数从api返回一些数据.问题是,当我尝试在订阅函数外部访问变量myVariable时,它返回未定义.我确定这是因为在我尝试访问myVariable

So this piece of code calls a function in my service that returns some data from an api. The issue is that when I try to access the variable myVariable right outside of the subscribe function it returns undefined. Im sure this is because the subscribe hasnt finished before I try to access myVariable

在尝试访问myVariable之前是否可以等待订阅完成?

Is there a way to wait for the subscribe to finish before I try to access myVariable?

谢谢!

推荐答案

为什么不创建单独的函数并在订阅中调用它.

why not create a separate function and call it inside the subscription.

export class myClass {
  myVariable: any;

  myFunction() {
    this.myService.getApi().subscribe(data => {
      this.myVariable = data;
      this.update()
    });

    this.update()
  }

  update(){
    console.log(this.myVariable);
  }
}

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

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