代码之家  ›  专栏  ›  技术社区  ›  cup_of

angular 2+等待subscribe完成更新/访问变量

  •  6
  • cup_of  · 技术社区  · 6 年前

    你好,我有一个问题,我的变量是未定义的。我确信这是因为可观测的还没有完成。下面是我的.Ts文件中我的代码的一部分,它引起了这个问题:(我放置了理解这个问题所需的最小代码,如果我需要提供更多的代码和上下文,请让我知道。阿尔索 myFunction 从HTML中的单击事件调用。)

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

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

    在我尝试访问之前,是否有方法等待订阅完成 My变量 ?

    谢谢!

    2 回复  |  直到 6 年前
        1
  •  8
  •   Sachila Ranawaka    6 年前

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

    export class myClass {
      myVariable: any;
    
      myFunction() {
        this.myService.getApi().subscribe(data => {
          this.myVariable = data;
          this.update()
        });
    
        this.update()
      }
    
      update(){
        console.log(this.myVariable);
      }
    }
    
        2
  •  4
  •   Aniruddha Das xing    6 年前

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

    假设你是从服务台打电话给它

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