【问题标题】:When is subscribe method of Angular Http module calledAngular Http 模块的订阅方法何时被调用
【发布时间】:2017-11-13 22:45:38
【问题描述】:

我有一个组件类和服务类。当收到 http 200 状态代码时,我有翻转标志的逻辑。根据收到的响应,我使用 if 条件翻转标志。

Requests(data:Array<String>):Observable<any>{
    return this.http.post(this.Url,data)
      .map(
        (res:Response) => {
          if(res.status === 200 || res.status===201) {
            return res.json()
          }
        }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }

组件文件是这样的。

methodName(selectedData){

    this.service.Requests(Id).subscribe((Response => {
      this.rResponse = Response;

    }));
    if(rResponse){
    // My logic to flip the flag
        }
      }
    }
    }

因此,根据从服务收到的响应,我将翻转标志。

但是当我在调试器工具中运行我的代码时,即使 rResponse 变量中有值,翻转标志的逻辑也不会被调用。实际上,在调用 methodName 函数时,代码流会先尝试在 if 循环下检查 rResponse 的值,然后在最后调用 subscribe 方法。

如果您可以请建议订阅方法的工作流程。为什么在调用实际 subscribe 方法之前调用 if 条件。

这不是重复的,因为我想了解为什么流程不进入我的 if 循环。没有什么是未定义的。我正在从服务中获取价值

【问题讨论】:

  • Observable Undefined的可能重复
  • 立即调用订阅方法。 你传递给它的回调不是,这就是异步请求处理的重点。

标签: angular angular2-services angular-http


【解决方案1】:

我的理解是你想在收到rResponse 的值时做一些逻辑。

您可能知道 subscribe 方法调用本质上是异步的,即一旦发出请求,它就会继续执行到下一行。

因此,正如您在订阅方法之外编写的 if 条件,如果条件在服务调用完成之前立即执行。这会导致空响应。

因此,您需要将 if 条件放在分配 this.rResponse = Response; 的同一块中

methodName (selectedData) {    
    this.service.Requests(Id).subscribe((Response => {
        this.rResponse = Response;
        if(this.rResponse) {
            // My logic to flip the flag
        }      
    }));        
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2018-01-01
    • 2017-12-19
    • 2020-10-08
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多