angular2 wait until observable finishes in if condition

廉价感情. 提交于 2019-12-20 11:21:47

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/41912629/angular2-wait-until-observable-finishes-in-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!