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

时间:2020-11-06 21:33:56

标签: angular typescript

当我单击“提交”时,我想为所选的每个日期发出多个HTTP请求。当我单击提交时,下面的代码仅将selectedDate的最后一个元素分配给booking.bookDate。

MyTableModel

模型> booking.ts:

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

服务> booking.service.ts:

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

2 个答案:

答案 0 :(得分:1)

您应该可以使用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) => {
    ...
  });
}

您应该分别返回包含响应的数组。

答案 1 :(得分:0)

您可以使用mergeMap()和toArray()使其表现更好。 当任何呼叫失败时,ForkJoin将取消。

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