报价来自RxJS开发团队:
为了解决所有这些问题,我们决定放弃
toPromise()
,并引入两个新的助手函数,用于将承诺转换为承诺。 使用两个新函数之一-- 作为对不推荐的toPromise()
方法的替代,您应该使用两个内置的静态转换函数firstValueFrom
或lastValueFrom
中的一个.
在我的例子中,我向服务器发送一个get请求,以检查服务器是否可用。在HTTP或错误返回之前,主函数(在本例中是ngOnInit()
)不会更进一步。
在本文的这一部分,他们建议将一个timeout
添加到lastValueFrom()
函数中,这个函数应该作为一个配置config?: LastValueFromConfig<D>
添加。
我的代码:
let something = lastValueFrom(this.http.get<resultDTO>
('/api/account/test'),).then(
res => {
this.note = (res.data);
}
);
如何设置此配置并将其传递给函数?
发布于 2021-11-22 14:04:51
必须将timeout
操作符添加到HTTP请求中,而不是添加来自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
行为无关。
所以在你的情况下你可以
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);
});
尽管如此,这是一个例子,我要说的是,没有内在的必要将可观察到的转化为承诺。你只需用可观察到的
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
}
});
https://stackoverflow.com/questions/70066962
复制相似问题