【问题标题】:How to work with delayed get Http API Response in Angular如何在 Angular 中使用延迟获取 Http API 响应
【发布时间】:2020-08-14 07:20:28
【问题描述】:

在这里,我收到了来自 this.ServiceHandler.getTxnInfo([], params) api 的延迟响应。因此我使用 setTimeoutasync/await。但我的承诺被拒绝了。

bookingInfo = [];

  timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

这是我调用 API 获取请求的地方。

async getBookingInfo(dateType: string) {
    const params = [];
    params.push({code: 'dateType', name: dateType});
    params.push({code: 'fromDate', name: '2019-01-01'});
    params.push({code: 'toDate', name: '2019-05-31'});
    return await this.ServiceHandler.getTxnInfo([], params).toPromise();
  }

getBookingDetails() {
    this.timeout(150057 ).then(() => this.getBookingInfo('BOOKING').then(
      bookings => {
        console.log(bookings);
      }));
  }

但我无法打印我的console.log(bookings);Promise 被拒绝并且我的获取请求失败。这是我收到的错误

我该如何解决。

【问题讨论】:

  • 为什么将 async/await 代码与 .then 回调混合在一起?
  • 我想保留我的 get http 请求,直到收到响应。它需要超过 2 分钟才能收到来自 API 的响应
  • 老实说,我不明白你想要达到什么目的。您正在等待 150 秒,然后您是否启动了 http 调用,将 BOOKING 作为日期类型提供给 api?这很可能会导致 API 以 400(错误请求)响应,这将导致您的承诺被拒绝,因为它不是 200
  • this.getBookingInfo('BOOKING') BOOKING 是我的参数。实际上我不明白那里发生了什么。在这里,我试图得到对 console.log(bookings); 的响应
  • 我在 getBookingDetails() 中添加了 this.timeout(150057) 以等待响应

标签: angular typescript promise async-await


【解决方案1】:

使方法 async 和 await 应该做你所期望的。

async getBookingInfo(dateType: string) {
 const params = [];
 params.push({code: 'dateType', name: dateType});
 params.push({code: 'fromDate', name: '2019-01-01'});
 params.push({code: 'toDate', name: '2019-05-31'});
 return await this.ServiceHandler.getTxnInfo([], params).toPromise();
}

async getBookingDetails() {
 await this.getBookingInfo('BOOKING').then(
  bookings => {
    console.log(bookings);
 });
}

【讨论】:

  • 那我可以在 ngOnit() 方法中使用异步 getBookingDetails() 方法
【解决方案2】:

首先,让我们更改此代码以更适合 Angular 并避免承诺。无需通过 toPromise() 将 observables 转换为 Promise

getBookingInfo(dateType: string): Oservable<SOME_TYPE_HERE> {
  const params = [];
  params.push({code: 'dateType', name: dateType});
  params.push({code: 'fromDate', name: '2019-01-01'});
  params.push({code: 'toDate', name: '2019-05-31'});
  return this.ServiceHandler.getTxnInfo([], params);
}

getBookingDetails(): void {
  this.getBookingInfo('BOOKING').subscribe(bookings => {
    console.log(bookings);
  });
}

这段代码没有承诺,让我们检查它是否有效。如果不是 - 那么我们至少知道承诺不是原因。

【讨论】:

  • 实际上我的问题是获得响应有延迟。因此一段时间后它在网络选项卡中失败了。我怎么能在响应到来之前保留我的请求
猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多