0

来自RxJS开发团队的引述:

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

使用两个新功能之一

作为不推荐使用的 toPromise()方法的替代,您应该使用两个内置静态转换函数之一firstValueFromlastValueFrom....

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

本文的这一部分,他们建议将 a 添加timeoutlastValueFrom()函数中,应将其添加为 config config?: LastValueFromConfig<D>

我的代码:

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

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

4

1 回答 1

2

必须将timeout操作符添加到 HTTP 请求而不是 Promise from lastValueFrom

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

timeout这与observable 的行为无关。

所以在你的情况下你可以做

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
  }
});
于 2021-11-22T14:04:51.087 回答