【问题标题】:Execute conditions after getting values from api call [duplicate]从api调用获取值后执行条件[重复]
【发布时间】:2022-01-20 01:24:27
【问题描述】:

我正在开发一个 Angular 应用程序。我的 ngOnInit() 中有一个 API 调用和一个 if 语句,如下所示:

  ngOnInit() {
      this.myService.getData(id).subscribe(res => {
        if (res != null) {
            this.myId = res.id;
         }
      }
      
    if (this.myId == 2) {
        //execute my code
     }
    }

我面临的问题是,如果在我从 API 调用中获取 Id 的值之前执行了一条语句,那么我的代码将无法工作。我尝试将 if 语句放在 setTimeout 下并且代码有效。但我想有一些更好的解决方案,而不是使用 setTimeout。我该怎么做?

【问题讨论】:

  • 您能展示一下您的服务代码的样子吗?我想看看返回的是什么类型的 observable?

标签: angular angular8 angular9


【解决方案1】:

试试这个,

  ngOnInit() {
      this.myService.getData(id).subscribe(res => {
        if (res != null) {
            this.calculate(res.id);
         }
      }
 }
 calculate(id){
  if(id==2){
    //do something 
  }else{
    //do something else
  }
}

如果您的条件超出使用 switch case。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2017-05-18
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多