2017-08-11 49 views
0

我試圖圍繞如何實現這一點我的頭。我的第一個GET返回對象的數組,像這樣:Anguarl HttPClient - 後續http.GETs的forEach循環?

{ 
    "stuff": [ 
    { 
     "creationTime": 1502476634000, 
     "id": 1 
    } 
    { 
     "creationTime": 1502476634001, 
     "id": 2 
    } 
    { 
     "creationTime": 1502476634002, 
     "id": 3 
    } 
    ] 
} 

對於每一個對象,我需要再作GET與對象ID到另一個端點。調用2nd GET的最佳方式是什麼?爲每個循環,並不斷調用GET與每個ID和推送響應數組?我查看了一些較舊的堆棧溢出答案,他們提到q.all(),但已棄用。

+1

一個循環會很好,在每個項目的循環內觸發另一個循環,然後在'then'將結果推送到一個數組(如果這是你想要做的)。如果你想要一個不太友好的界面*和*你有服務器上的源代碼控制,你可以改變它來獲取一個ID數組並返回一組結果。 – Igor

+2

你看過https://stackoverflow.com/questions/41204055/rxjs-with-multiple-forkjoin-when-doing-http-requests?快速搜索互聯網提供了大量關於並行請求的資料。 – jonrsharpe

+0

你有什麼試過...? –

回答

0

看看這個鏈接。我有同樣的問題,並解決它爲我:

http://blog.danieleghidoli.it/2016/10/22/http-rxjs-observables-angular

下面是一些僞代碼,因爲你沒有提供太多的信息:

return this.http.get('/api/getStuff').flatMap((stuff: any[]) => { 
    if (stuff.length > 0) { 
     return Observable.forkJoin(stuff.map((stuff: any) => { 
      return this.http.get('/api/getAdditionalStuff' + stuff.id).map((res: any) => { 
       // do what you need to do with additional stuff 
       // in my case I added the additional stuff to a property of the 
       // original call 
       stuff.additionalStuff = resp; 
       return stuff; 
      }); 
     })); 
    } 
    return Observable.of([]); 
}); 
0

HttpClient我假設你正在使用Angular4 +。

服務:

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 
@Injectable() 
export class MyService { 

    constructor(private http: HttpClient) { } 

    getArray() { 
    return this.http.get('http://myapi/getarray'); 
    } 

    getItemPassingId(id) { 
    return this.http.get(`http://myapi/getItem/${id}`); 
    } 
} 

COMPONENT:

import { Component, OnInit } from '@angular/core'; 
import { first, mergeMap } from 'rxjs/operators'; // import pipeable (formerly lettable) operators 
import { forkJoin } from 'rxjs/observable/forkJoin'; 
@Component({ 
    selector: 'my-component', 
    templateUrl: 'my-component.html' 
}) 

export class MyComponent implements OnInit { 
    constructor(private myService: MyService) { } 

    ngOnInit() { } 

    onAction() { 
    this.myService.getArray() // get the array 
     .pipe(
     first(), // this would complete the observable on first value (no need to unsubscribe) 
     mergeMap((array: Array<{creationTime: number, id: number}>) => { 
      return forkJoin(array.map((item) => { // loop through the array and return the call based on each item's id 
      return this.myService.getItemPassingId(item.id); 
      })); 
     }) 
    ) 
     .subscribe((results) => { // you'll get the finalized results here as an array 
     console.log(results); 
     }); 
    } 
} 

希望這有助於。