Search code examples
javascriptangulartypescriptrxjsobservable

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


I am having an issue with my variables being undefined. I am certain this is because the observable hasn't 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. 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. I'm sure this is because the subscribe hasn't finished before I try to access myVariable

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


Solution

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