2017-08-19 30 views
0

這是我的一個堆疊http.get代碼,檢索一個對象,然後將對象的詳細信息:Angular2的Rx - 疊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結果?

+0

可能重複的[如何在Angular2中鏈接Http調用](https://stackoverflow.com/questions/34104638/how-to-chain-http- calls-in-angular2) – Vega

+0

HTTP請求是異步的。您最外面的'console.log'調用將始終輸出'undefined'。 – cartant

+2

考慮使用ForkJoin –

回答

1

你想等待第二個請求,直到返回響應,所以你應該使(鏈式兩個調用) 看到(How to chain Http calls in Angular2)。

+0

感謝!我終於明白,我無法在http.get鏈中的任何位置使用'subscribe',否則直接返回。當在整個鏈中只使用'map'和'flatmap'時,它工作得很好! – AndyZ

0

除了與完成事件內部處理它,你還可以添加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 。第二次訂閱它將有數據和相應的流程將如下