简体   繁体   中英

Angular 8 - Multiple HTTP calls in a for loop

There is a list of unlimited cars in backend. Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];

and I need to fetch respective car names for the above car Ids. I tried the below code, but its not working at all, what is that I'm missing?

const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]

Thanks in advance.

You can use forkJoin to subscribe to many streams by once and get the result when all stream are complete, it is like a promise.all for rxjs.

const carIds = ['abc','xyz']; // unique ids
const httpCalls = carIds.map(id => this.api.getCar(id)) // array of streams
const carsList$ = forkJoin(httpCalls).pipe(
   map(results => results.map((r, index) => ({ id: carIds[index], name: r.name }));
);

carsList$.subscribe(console.log);
const carsList = [];

for await (const carId of carIds) {
  const car = await this.api.getCar(carId);
  car && carsList.push({
        name: car.name,
        id: carId
      });
}

Try this code. Happy to help:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM