angular2等到可观察完成后如果条件

时间:2017-01-28 17:23:14

标签: angular observable

我已经实现了像这样的if语句

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

如果条件等待来自后端的响应。但是在observable执行之前,它会进入else语句并完成条件而不会在开始时检查if条件。

这是我从后端获取数据的可观察方法

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

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

那么如何使条件等待,直到它从后端获得响应

1 个答案:

答案 0 :(得分:23)

您无法等待areTherePossibleValues(">=5 & <50 & >30 & >45") #[1] "TRUE for (45.0000000001 < x < 49.9999999999)" areTherePossibleValues("x>5 & x<3") #[1] FALSE areTherePossibleValues(c("<5",">=2 & =4")) #[1] "TRUE for (4 < x < 4)" Observable完成。您只能订阅它以在完成或发出事件时收到通知。

Promise

然后你可以做

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

但是如果此代码的调用者也依赖于返回值,则需要再次

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

然后执行您调用此代码的this.service.check() .map(value => { if (value) { return true; } else { } }