From the HttpClient
I'm assuming you're working with Angular4+.
SERVICE:
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);
});
}
}
Hope this helps.