【问题标题】:How to reload page in Angular Typescript to 'await' HTTP calls with BE如何在 Angular Typescript 中重新加载页面以使用 BE“等待”HTTP 调用
【发布时间】:2021-03-30 13:28:39
【问题描述】:

在下面的代码中:

  1. http 调用获取多个订单行的(项目)ID
  2. 为每个人再次进行 http 调用并保留它们。 然后,我需要重做那些显示为保留的页面。

由于项目众多,最后 3 行会在页面实际保留在 BE 中之前执行并重新加载页面,因此我添加了 0.7 秒延迟,但这不是最佳实践,我不知道该怎么做( switchMap?如何)

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

【问题讨论】:

    标签: angular typescript asynchronous async-await subscribe


    【解决方案1】:

    你可以使用 Rxjs 的管道来操作流

    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

    【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2017-03-15
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多