从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
你有什么试过...? –