如何修复 Angular HttpClient toPromise() 已弃用 (rxjs)

问题:

你有类似这样的 angular HTTP 客户端代码

httpclient_toPromise.ts
this.http.get<MyType>(`${this.baseURL}/api/myAPI`).toPromise()

toPromise() 在最近版本的 angular / rxjs 中已弃用。

toPromise_deprecation.ts
/** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
toPromise(): Promise<T | undefined>;

解决方案

在大多数情况下,对于 HttpClient,你想使用 rxjs 的 firstValueFrom(),因为 HttpClient Observable 通常只返回一个值。

首先,从 rxjs 导入 firstValueFrom

import_firstValueFrom.ts
import { firstValueFrom } from 'rxjs';

然后删除 .toPromise() 调用:

remove_toPromise.ts
// 之前
this.http.get<MyType>(`${this.baseURL}/api/myAPI`).toPromise()
// 之后
this.http.get<MyType>(`${this.baseURL}/api/myAPI`)

并用 firstValueFrom 包围整个语句:

use_firstValueFrom.ts
// 之前
this.http.get<MyType>(`${this.baseURL}/api/myAPI`)
// 之后
firstValueFrom(this.http.get<MyType>(`${this.baseURL}/api/myAPI`).toPromise())

这将修复问题。


Check out similar posts by category: Angular, Typescript