如何使用BE重新加载Angular Typescript中的页面以“等待" HTTP调用

问题描述:

在下面的代码中:

  1. http调用会获得多个订单项的(项目)ID
  2. 对于每个
  3. 进行另一个http调用并保留它们.然后,我需要重做页面,将那些页面显示为保留.

尽管有很多项目,但最后3行会在它们真正保留在BE中之前执行并重新加载页面,因此我添加了0.7秒的延迟,但这不是最佳实践,否则我不知道该怎么做(switchMap?如何)

Whith numerous items, the last 3 lines would execute and reload the page before they actually got reserved in the BE so I added that 0.7 sec delay but that's not best practice and I can't figure out how to do it otherwise (switchMap? how)

   this.service.getOrderlineId(this.orderlineIds).subscribe((ids: Number[]) => {
      ids.forEach(id => {
        this.currentReservation = {
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address
        }
        this.service.createOrderLineReservation(this.currentReservation).subscribe(reservation => {

        })
      })
    })

    setTimeout(() => {                       
      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
    }, 700);

您可以使用Rxjs的管道来操纵流

You could use Rxjs's pipe to manipulate the streams

this.service
  .getOrderlineId(this.orderlineIds)
  .pipe(
    map((ids: number[]) =>
        // Map the ids to an Observable list
      ids.map((id) =>
        this.service.createOrderLineReservation({
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address,
        })
      )
    ),
    switchMap((reservations$: Observable[]) => 
    // After all observables emit, emit values as an array
    zip(...reservations$))
  )
  .subscribe((reservations: Reservation[]) => {
      // You get an ordered list of reservations

      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
  });

ps:不要使用setTimout

ps: Don't use setTimout