2017-07-18 55 views
1

我想在angular2中寫下jquery代碼。我怎樣才能做到這一點?angular2中的多個ajax調用

$.when($.ajax("url"), $.ajax("/url2")) 
    .then(myFunc, myFailure); 

and 

$.when($.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3")).then(function(resp1, resp2, resp3){ 
    // plot graph using data from resp1, resp2 & resp3 
}); 
+1

https://stackoverflow.com/questions/34405039/combining-promises-in-angular-2 – yurzui

+0

在[結合的承諾可能的複製Angular 2](https://stackoverflow.com/questions/34405039/combining-promises-in-angular-2) – CozyAzure

回答

1

首先您已經學習瞭如何使用Angular Http模塊。

然後學習如何使用RxJS來組合/連接您的http請求。

參考對於HTTP:https://angular.io/tutorial/toh-pt6 參考了forkJoin:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md

let request$ = this.http.get('https://yourapi/api/').map(res => res.json()); 
let request2$ = this.http.get('http://another/api2').map(res => res.json()); 

Observable.forkJoin([request$, request2$]).subscribe(results => { 

}); 
+0

謝謝,你能告訴我,如何使用結果數據到不同的組件abc.component.ts,bcd .component.ts(這裏,第一個組件需要第一個請求的響應,第二個組件需要第二個請求的響應,等等) –

+0

很多dep結束於你如何構建你的組件,但我認爲你需要編寫一個服務來獲取http響應,然後爲每個組件注入一個服務。 但是,如果2個不同的組件需要不同的數據,我不認爲在這裏如何組合響應是有利可圖的。也許你想在渲染任何圖之前獲取所有數據? –