【问题标题】:How to set a timeout config for lastValueFrom() using RxJS 7 in Angular 13?如何在 Angular 13 中使用 RxJS 7 为 lastValueFrom() 设置超时配置?
【发布时间】:2022-01-01 02:58:34
【问题描述】:

Quote 来自 RxJS 开发团队:

为了解决所有这些问题,我们决定弃用 toPromise(),并引入两个新的帮助函数来转换为 Promise。

使用两个新功能之一

作为已弃用的替代品 toPromise() 方法,你应该使用两个内置静态之一 转换函数firstValueFromlastValueFrom....

在我的例子中,我向服务器发送了一个获取请求以检查服务器是否可用。 main 函数(在本例中为 ngOnInit())在 HTTP 响应或错误返回之前不会更进一步。

this part of the article,他们建议在lastValueFrom() 函数中添加timeout,它应该作为配置添加config?: LastValueFromConfig<D>

我的代码:

    let something = lastValueFrom(this.http.get<resultDTO> 
    ('/api/account/test'),).then(
          res => {
            this.note = (res.data);
          }
    );

如何设置此配置并将其传递给函数?

【问题讨论】:

标签: angular typescript rxjs angular13 rxjs7


【解决方案1】:

timeout 运算符必须添加到 HTTP 请求,而不是来自 lastValueFrom 的 Promise。

let something = lastValueFrom(
  this.http.get<resultDTO>('/api/account/test').pipe(
    timeout(5000)      // <-- HTTP request will error out if no response for 5 seconds
  )
).then(res => {
  this.note = (res.data);
});

目前的LastValueFromConfig 参数(RxJS v7)只有一个值。

export interface LastValueFromConfig<T> {
  defaultValue: T;
}

这与 observable 的 timeout 行为无关。

所以你可以这样做

let something = lastValueFrom(
  this.http.get<resultDTO>('/api/account/test').pipe(
    timeout(5000)      // <-- HTTP request will error out if no response for 5 seconds
  ),
  { defaultValue: { data: ''} }  // <-- default value to be used
).then(res => {
  this.note = (res.data);
});

话虽如此,这是我认为不需要将 Observable 转换为 Promise 的情况之一。你可以简单地只使用可观察的

this.http.get<resultDTO>('/api/account/test').pipe(
  timeout(5000)      // <-- HTTP request will error out if no response for 5 seconds
).subscribe({
  next: (res: resultDTO) => {
    this.note = res.data;
  },
  error: (error: any) => {
    // handle errors
  }
});

【讨论】:

猜你喜欢
  • 2019-06-25
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 2012-11-11
  • 1970-01-01
相关资源
最近更新 更多