Angular 2+ wait for subscribe to finish to update/access variable

cup_of picture cup_of · Jun 20, 2018 · Viewed 55.4k times · Source

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

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

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

Thanks!

Answer

Sachila Ranawaka picture Sachila Ranawaka · Jun 20, 2018

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