Angular 2+等待订阅完成更新/访问变量

cup*_*_of 9 subscribe observable angular

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

export class myClass {
  myVariable: any;

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

    console.log(myVariable) --> undefined
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

Sac*_*aka 8

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

export class myClass {
  myVariable: any;

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

    this.update()
  }

  update(){
    console.log(this.myVariable);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • `myVariable` 当我尝试这个方法时,在 `myFunction` 中返回 undefined,然后在 `update()` 中返回 null。`myVariable` 的预期结果是什么,是否可以从中获取状态代码(201/4,发布请求)?显然, undefined 和 null 在使用 `myVariable.status` 时会抛出错误 (2认同)

Ani*_*Das 5

如您所知,订阅是在服务器返回数据时执行的,但是订阅代码的外部同步执行。这就是为什么要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()
    });
  }

}
Run Code Online (Sandbox Code Playgroud)