Angular 如何使用For循环发出多个HTTP请求?打字稿

Angular 如何使用For循环发出多个HTTP请求?打字稿,angular,typescript,Angular,Typescript,当我单击提交时,我想对我选择的每个日期发出多个HTTP请求。当我单击提交时,下面的代码仅将selectedDate的最后一个元素指定给booking.bookDate selectedDate: any = []; booking: SaveBooking = { id: 0, roomId: 0, buildingId: 0, bookDate: '', timeSlots: [], modules: [], semesterId: 0, }; submit()

当我单击提交时,我想对我选择的每个日期发出多个HTTP请求。当我单击提交时,下面的代码仅将selectedDate的最后一个元素指定给booking.bookDate

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()    
});
型号>预订.ts:

export interface SaveBooking {
    id: number;
    semesterId: number;
    roomId: number;
    buildingId: number;
    bookDate: string;
    timeSlots: number[];
    modules: number[];
}
服务>预订.service.ts:

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

您应该能够使用forkJoin这样做:

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) => {
    ...
  });
}
您应该分别返回一个包含响应的数组。

您可以使用mergeMap()和toArray()使其性能更好。 当任何调用失败时,ForkJoin将取消

submit(){
const result$=
从(this.selectedDate)
.烟斗(
合并地图(日期=>{
this.booking={…this.booking,bookDate:date};
返回this.bookingService.create(this.booking);
}),
toArray()
);
}

如果您是API的所有者,则应考虑添加批量插入API端点。通过这种方式,您可以通过
{booking,dates:[date1,date2,…]}
@Shinigami向您的API发送一个调用。这也解决了许多问题,例如事务和错误处理。结果返回一个数组,但数组中的每个元素都具有相同的selectedDate最后一个值。我希望它根据我选择的日期有不同的日期。你知道怎么解决这个问题吗?