【问题标题】:Angular 2+ wait for subscribe to finish to update/access variableAngular 2+ 等待订阅完成以更新/访问变量
【发布时间】:2018-11-29 19:08:01
【问题描述】:

您好,我的变量未定义有问题。我确信这是因为可观察的还没有完成。这是我的 .ts 文件中导致问题的代码部分:(我放置了理解问题所需的最少代码,如果我需要提供更多代码和上下文,请告诉我。还有myFunction 获取从 html 中的点击事件调用。)

export class myClass {
  myVariable: any;

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

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

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

在我尝试访问myVariable之前,有没有办法等待订阅完成?

谢谢!

【问题讨论】:

    标签: angular observable subscribe


    【解决方案1】:

    如您所知,订阅在服务器返回数据时执行,但订阅代码的外部同步执行。这就是为什么在它之外执行console.log。以上答案可以完成您的工作,但您也可以使用.mapreturn observable,如下所示。

    假设你是从 s 服务调用它

    export class myClass {
      myVariable: any;
    
      // calling and subscribing the method.
      callingFunction() {
    
        // the console log will be executed when there are data back from server
        this.myClass.MyFunction().subscribe(data => {
          console.log(data);
        });
      }
    }
    
    
    export class myClass {
      myVariable: any;
    
      // this will return an observable as we did not subscribe rather used .map method
      myFunction() {
        // use .pipe in case of rxjs 6 
        return this.myService.getApi().map(data => {
          this.myVariable = data;
          this.update()
        });
      }
    
    }
    

    【讨论】:

    • 第二块代码是服务,第一块是调用服务的组件吗?如果有的话,更新功能是做什么的,我为什么需要它?
    【解决方案2】:

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

    export class myClass {
      myVariable: any;
    
      myFunction() {
        this.myService.getApi().subscribe(data => {
          this.myVariable = data;
          this.update()
        });
    
        this.update()
      }
    
      update(){
        console.log(this.myVariable);
      }
    }
    

    【讨论】:

    • 这似乎对我有用。谢谢!一个简单的问题,为什么需要两个 this.update() 实例?一个在订阅中,一个在订阅之外
    • 您可以根据需要将其删除。如果你想在组件初始化时调用它,我会添加它
    • myVariable 当我尝试此方法时,在 myFunction 中返回 undefined ,然后在 update() 中返回 null 。 myVariable 的预期结果是什么,是否可以从中获取状态代码(201/4,发布请求)?显然,undefined 和 null 在使用myVariable.status时会报错
    • 如果订阅者写在服务类中怎么办?
    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多