2

I have function like:

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

And I am calling that function in other function as follows :

set() {
    if (this.value == 1) {
        this.getNumber(firstNumber)
        this.newVariable = this.myVariable;
    } else {
        this.getNumber(secondNumber)
        this.newVariabe = this.myVariable + 1;
    }
};

this.value is getting from other function. The problem is that this.newVariable is empty. I'm sure this is because the subscribe hasn't finished before I try to access this.Variable

Is there any way to wait for the subscribe to finish before I do anything else?

Sasuke Uchiha
  • 421
  • 6
  • 17
Bary
  • 53
  • 1
  • 2
  • 11
  • `getNumber` should return the Observable, and you should subscribe to it in the "other" function, when you need the value. – ConnorsFan Feb 26 '19 at 15:18
  • 3
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – ConnorsFan Feb 26 '19 at 15:20

1 Answers1

3

Just return an Observable from getNumber and subscribe to it.

You can also add pipe to getNumber so it will handle storing data and also return an Observable to subscribe to.

getNumber(value) {
    return this.myService.getApi(value).pipe(tap(data => {
        this.myVariable = data;
    }));
}

And in your set method

set() {
    if (this.value == 1) {
      this.getNumber(firstNumber).subscribe(() => {
        this.newVariable = this.myVariable;
      });
    }
    else {
      this.getNumber(secondNumber).subscribe(() => {
        this.newVariabe = this.myVariable + 1;
      });
   }
};
Arif
  • 1,617
  • 9
  • 18