2017-09-11 28 views
0

我在使用Angular 4中的RxJS編寫異步調用。RxJS - 解決多個服務器調用

我需要調用服務器,得到響應,並用它來撥打另一個電話,得到這樣的迴應,並用它來撥打另一個電話等。我正在使用下面的代碼爲此,並按預期工作

id; 
name; 
ngOnInit() { 
    this.route.params 
     .flatMap(
     (params: Params) => { 
     this.id = params['id']; 
     return this.myService.get('http://someurlhere'); 
     } 
    ) 
     .flatMap(
     (response: Response) => { 
     return this.myService.get('http://someurlhere'); 
     }) 
     .flatMap(
     (response: Response) => { 
     return this.myService.get('http://someurlhere'); 
     }) 
     .subscribe(
     (response: Response) => { 
     FileSaver.saveAs(blob, this.name); 
     }, 
     (error) => {   
     console.log('Error ' + error) 
     } 
    ) 
    } 

現在,我需要做一些更改。在第一個flatMap中,我需要進行2次其餘呼叫,並且只有在兩個呼叫都被解析後才能繼續。這不僅只是其中之一的響應將被傳遞到下一個flatMap,因爲其他呼叫只會填充一個變量

id; 
name; 
ngOnInit() { 
    this.route.params 
     .flatMap(
     (params: Params) => { 
     this.id = params['id']; 
     // this is the 2nd REST call. It just populates a variable, so don't need the output to be passed to next flatMap. However, both the URLs in this section should resolve before the next flatMap is executed. 
     this.name = this.myService.get('http://someotherurlhere'); 
     return this.myService.get('http://someurlhere'); 
     } 
    ) 
     .flatMap(
     (response: Response) => { 
     return this.myService.get('http://someurlhere'); 
     }) 
     .flatMap(
     (response: Response) => { 
     return this.myService.get('http://someurlhere'); 
     }) 
     .subscribe(
     (response: Response) => { 
     FileSaver.saveAs(blob, this.name); 
     }, 
     (error) => {   
     console.log('Error ' + error) 
     } 
    ) 
    } 

所以,我的問題是,應該如何這段代碼被寫入使它從服務器獲取響應,但在移動到下一個平面映射之前,等待另一個其他呼叫也完成。

this.name = this.repoService.getDocProperties(this.objectId); 
+1

您可以使用forkJoin等到多個請求完成https://coryrylan.com/blog/angular-multiple-http-requests- with-rxjs –

回答

0

您可以將異步與forkJoin

你的情況,要求你有兩個電話:

​​

它們可以組合,像這樣:

let call1 = this.myService.get('http://someotherurlhere'); 
let call2 = this.myService.get('http://someurlhere'); 
return Observable.forkJoin([call1, call2]) 

當您訂閱(或鏈接一些其他函數)連接的observable返回的數據將在一個數組中。所以從call1結果會在索引0和call2索引1

Observable.forkJoin([call1, call2]).subscribe((results) => { 
    results[0]; // call1 
    results[1]; // call2 
}); 
+0

謝謝。那麼,將傳遞給下一個flatMap的輸出是什麼。我只需要通過CALL2的輸出(而不是CALL1)到下一個flatMap – kayasa

+0

@kayasa我編輯的答案讓我知道如果你需要更多的澄清 –

+0

如果我做了Observable.forkJoin,那麼在此之後的下一個flatMap拋出錯誤 - 'Property'flatMap'在'Subscription'類型中不存在。' – kayasa