29

I have implemented a if statement like this

if (this.service.check() ) {
      return true;
    }
    else {
}

this if condition waits for a response from the backend. But before the observable gets executed it's going into the else statement and finishing the condition without checking the if condition at start.

this is my observable method to get the data from backend

public check(){
      this.getActorRole().subscribe(
        (resp => {
          if (resp == true){
             return true
         }

        }),
        (error => {
          console.log(error);
        })
      );
    }
}

So how make the condition waits until it gets the response from the backend

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Kokulan
  • 1,316
  • 3
  • 19
  • 35

1 Answers1

34

You can't wait for an Observable or Promise to complete. You can only subscribe to it to get notified when it completes or emits an event.

public check(){
   return this.getActorRole() // <<<=== add return
   .map(resp => {
          if (resp == true){
             return true
         }
      );
    }
}

then you can do

this.service.check().subscribe(value => {
  if (value) {
    return true;
  }
  else {
  }
}

but if the caller of this code also depends on the return value you again need to

this.service.check()
.map(value => {
  if (value) {
    return true;
  }
  else {
  }
}

and then do the subscribe() where you call this code

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I already have the .map implemented the problem is it's getting the else condition executed before the check() function finshe's execution. So it's always going to the else condition – Kokulan Jan 28 '17 at 17:36
  • because the code needs to be within a `map(...)`, `subscribe(...)` or any other observable operator. – Günter Zöchbauer Jan 28 '17 at 17:38
  • inside an `async` function one may `await` for a Promise to resolve though (these days) – YakovL Aug 29 '19 at 18:05