angular2等到条件可观察到完成 [英] angular2 wait until observable finishes in if condition

查看:75
本文介绍了angular2等到条件可观察到完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个if语句

I have implemented a if statement like this

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

如果条件等待后端的响应,则为

.但是在可观察对象执行之前,它将进入else语句并完成条件,而无需在启动时检查if条件.

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

推荐答案

您不能等待ObservablePromise完成.您只能订阅它才能在事件完成或发出事件时得到通知.

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
         }
      );
    }
}

那你就可以做

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 {
  }
}

,然后执行subscribe()调用此代码的地方

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

这篇关于angular2等到条件可观察到完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆