2017-08-22 43 views
3

我有一個圖像對象數組。Angular 4中的多個順序API調用

console.info('gallery', galleryArray); 

enter image description here

此數組的長度可以是不同的。我必須對這個數組的每個項目發出POST請求。下一個請求必須在前一個請求完成後才能執行。

所以我試圖使可觀測請求一個這樣的數組:

let requests: Observable<Response>[] = []; 
    galleryArray.forEach((image) => { 
    requests.push(this._myService.uploadFilesImages(image)); 
    }); 

    console.info(requests); 

enter image description here

我的服務是這樣的:

uploadFilesImages(fileToUpload: any): Observable<any> { 
    const input = new FormData(); 
    input.append('image', fileToUpload); 
    return this.uploadHttp.post(`${this.endpoint}`, input) 
    .map(
    (res: Response) => res.json() 
); 
} 

的問題是如何執行這些請求,所以每個API調用只有在前一個完成後才能進行?請幫助。我是Angular的新手。

+0

貴'_myService.uploadFilesImages'返回任何承諾或觀察到的? – Faisal

+1

@Faisal它返回可觀察。請參閱編輯 – Luchnik

回答

6

您正在尋找concatMap操作:

const apiRoot = 'https://jsonplaceholder.typicode.com/'; 
const urls = []; 
for (let i = 0; i < 500; i++) { 
    urls.push(apiRoot + 'posts/' + (i + 1)); 
} 
Observable.of(...urls) 
    .concatMap((url: string) => this.http.get(url)) 
    .subscribe((result) => console.log(result)); 

concatMap運營商只迭代可觀察完成後的電流發射。您可以在subscribe區塊中獲得單個呼叫的結果。

你的具體情況:

Observable.of(...galleryArray) 
    .concatMap((image) => this._myService.uploadFilesImages(image)) 
    .subscribe((result) => console.log(result)); 
2

您可以使用async/await與無極解決宗旨:

let requests: Observable<Response>[] = []; 
galleryArray.forEach((image) => { 
    await new Promise(resolve => { 
     this._myService.uploadFilesImages(image) 
      .subscribe(result => { 
       requests.push(result);   
       // resolve the promise once we have a result 
       resolve(); 
      }); 
    });  
}); 

// This will only be called once all the api calls have been made 
console.info(requests); 

確保將async你在哪裏執行該代碼的方法後面。鏈接到我的answer有類似的問題。