0

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));
}
2
  • 1
    If you are the owner of the API, you should think about adding a bulk-insert API endpoint. This way you could send one call to your API with { booking, dates: [date1, date2, ...] } Commented Nov 6, 2020 at 21:43
  • 1
    @Shinigami is right. This also solves a lot of problems such as transactions and error handling. Commented Nov 6, 2020 at 21:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The result returns an array but each element in the array have the same last value of selectedDate. I want it to have different dates based on my selectedDate. Do you know how to solve this?
0

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()
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.