Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 wait until observable finishes in if condition

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

like image 588
kohli Avatar asked Jan 28 '17 17:01

kohli


1 Answers

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

like image 78
Günter Zöchbauer Avatar answered Nov 14 '22 08:11

Günter Zöchbauer