angular2 等待 if 条件下的 observable 完成

2024-03-16

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

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

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

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

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

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

那么如何让条件等待直到得到后端的响应


你等不及了Observable or 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 {
  }
}

然后做subscribe()你在哪里调用这段代码

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

angular2 等待 if 条件下的 observable 完成 的相关文章

随机推荐