2016-08-10 81 views
6

此問題已被要求here。然而,由於提問者的應用環境涉及太多的問題,我無法理解基礎知識。例如,有一個queryArr參數。它有什麼作用?如何進行角度同步http呼叫2

無論如何,我需要一點關於如何以最簡單的方式進行同步http調用的指導。我提出的解決方案是,必須以「嵌套」順序訂閱觀察數據。例如,有可觀察到的oxoy。被稱爲在oy請求的數據依賴於數據來自ox

xData: string = ""; 
yData: string = ""; 

ox.subscribe(
    data => {xData = data;}, 
    error => console.log(error), 
    () => { 
     oy.subscribe(
      data => {yData = xData*data;}, 
      error => console.log(error), 
      () => console.log("aaa") 
     ); 
    } 
); 

上次我記得(我不這樣做的JavaScript多,我有點新手),在我訂閱範圍到oyxDatayData不能再被看到。如果我錯了,請糾正我並指向正確的方向。

有沒有什麼「好」的解決方案或更好的方法來做這種事情?

回答

5

我認爲你可以看看flatMap運算符執行一個HTTP請求,等待它的響應並執行另一個。

這裏有一個例子:

executeHttp(url) { 
    return this.http.get(url).map(res => res.json()); 
} 

executeRequests() { 
    this.executeHttp('http://...').flatMap(result => { 
    // result is the result of the first request 
    return this.executeHttp('http://...'); 
    }).subscribe(result => { 
    // result is the result of the second request 
    }); 
} 

如果你想有機會獲得在subscribe方法兩個結果,你可以利用Observable.forkJoinObservable.of

executeRequests() { 
    this.executeHttp('http://...').flatMap(result => { 
    // result is the result of the first request 
    return Observable.forkJoin([ 
     Observable.of(result), 
     this.executeHttp('http://...'); 
    }).subscribe(results => { 
    // result is the result of both requests 
    let result1 = results[0]; 
    let result2 = results[1]; 
    }); 
} 
+5

這似乎使多個連鎖http請求,但問題很簡單,如何進行同步http請求,我不明白這是如何回答的。 – Neutrino

+0

一個http請求將永遠不會同步,您需要有適當的軟件設計(基於Observable),並且應該查看提及的[Observable.forkJoin](https://www.learnrxjs.io/operators/combination/forkjoin .html)運營商爲了並行化http呼叫並在所有完成後獲得訂閱。 – Markus