如何使用BE重新加载Angular Typescript中的页面以“等待" HTTP调用 [英] How to reload page in Angular Typescript to 'await' HTTP calls with BE

查看:121
本文介绍了如何使用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

这篇关于如何使用BE重新加载Angular Typescript中的页面以“等待" HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆