【问题标题】:Angular2 Rx - stacked http.get() returns too early [duplicate]Angular2 Rx-堆叠的http.get()返回得太早[重复]
【发布时间】:2017-08-19 17:17:45
【问题描述】:

这是我的堆栈 http.get 代码,它检索一个对象,然后检索对象的详细信息:

getDetails(sysID:string){

  console.log("entered getDetails");

  var details;
  this.http.get('https://blahURL').map(res => res.json()).subscribe(
   (data) => details = data,        // Reach here if res.status >= 200 && <= 299
   (err) => console.log(err),       // Reach here if fails
   ()==>{                           // On completion

     console.log("reached end of first get");

     this.http.get(...).map(res2 => res2.json()).subscribe(
        (data2) => {return data2;
        ...

这是通过console.log(getDetails(sysID)); 调用的。所以我期望的是,当第二个 this.http.get() 收到结果时,它会被传递给调用者并在控制台中打印。 但是,我在控制台中得到的是: entered getDetails然后是undefined,然后是reached end of first get

如何强制它等待第二个 http.get 结果?

【问题讨论】:

  • HTTP 请求是异步的。您最外层的console.log 调用将始终输出undefined
  • 考虑使用 ForkJoin
  • @cartant 我找到了一种方法让它只在最后返回,而不是在 http.get 链中使用subscribe

标签: angular typescript rxjs


【解决方案1】:

你想等待第二个请求直到返回响应,所以你应该进行(链接两次调用) 见(How to chain Http calls in Angular2)。

【讨论】:

  • 谢谢!我终于发现我不能在 http.get 链中的任何一点使用subscribe,否则它直接返回。在整个链中仅使用 mapflatmap 时,它工作得很好!
【解决方案2】:

除了在完成事件中处理之外,如果对象为空或未定义,您还可以添加skipWhile 以防止subscription

this.http.get('https://blahURL').map(res => res.json())
   .skipWhile(data=> {if(data) return true;}) ///////////////////////
   .subscribe(
   (data) => details = data,        // Reach here if res.status >= 200 && <= 299
   (err) => console.log(err),       // Reach here if fails
   ()==>{                           // On completion

     console.log("reached end of first get");

     this.http.get(...).map(res2 => res2.json()).subscribe(
        (data2) => {return data2;
        ...

所以在第一次订阅中,会按照skipWhile跳过。第二次订阅它将有数据,相应的流程将保持原样

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2020-04-09
    • 2012-01-11
    • 2016-04-12
    • 2016-10-20
    • 2019-10-08
    相关资源
    最近更新 更多