從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);
});
}
}
希望這有助於。
一個循環會很好,在每個項目的循環內觸發另一個循環,然後在'then'將結果推送到一個數組(如果這是你想要做的)。如果你想要一個不太友好的界面*和*你有服務器上的源代碼控制,你可以改變它來獲取一個ID數組並返回一組結果。 – Igor
你看過https://stackoverflow.com/questions/41204055/rxjs-with-multiple-forkjoin-when-doing-http-requests?快速搜索互聯網提供了大量關於並行請求的資料。 – jonrsharpe
你有什麼試過...? –