Max R
Max R

Reputation: 5

How to make multiple HTTP requests using For loop? TypeScript

When I click submit, I want to make multiple HTTP requests for every date that I've selected. The code below only assigns the last element of selectedDate to booking.bookDate when I clicked submit.

selectedDate: any = [];
booking: SaveBooking = {
  id: 0,
  roomId: 0,
  buildingId: 0,
  bookDate: '',
  timeSlots: [],
  modules: [],
  semesterId: 0,
};

submit() {
  var result$;

  for (let date of this.selectedDate) {
    this.booking.bookDate = date;
    result$ = this.bookingService.create(this.booking);
  }
}

result$.subscribe(() => {
  ...this.toasty.success()    
});

models > booking.ts:

export interface SaveBooking {
    id: number;
    semesterId: number;
    roomId: number;
    buildingId: number;
    bookDate: string;
    timeSlots: number[];
    modules: number[];
}

services > booking.service.ts:

create(booking) {
  return this.http.post(this.bookingsEndpoint, booking)
    .pipe(map(response => response));
}

Upvotes: 0

Views: 1298

Answers (2)

user3366195
user3366195

Reputation: 99

You can use mergeMap() and toArray() to make this perform better. ForkJoin would cancel when any of the calls would fail.

submit() {
  const result$ =
  from(this.selectedDate)
  .pipe(
    mergeMap(date => {
      this.booking = {...this.booking, bookDate: date};
      return this.bookingService.create(this.booking);
    }),
    toArray()
  );
}

Upvotes: 0

David G.
David G.

Reputation: 1485

You should be able to do that with forkJoin like so:

submit() {
  var observables = [];

  for (let date of this.selectedDate) {
    this.booking.bookDate = date;
    // Add each observable in the array
    observables.push(this.bookingService.create(this.booking));
  }

  forkJoin(observables).subscribe((arrayOfResults) => {
    ...
  });
}

You should get back an array with the responses respectively.

Upvotes: 1

Related Questions