angular RXJS 如何转换订阅响应类型

时间:2021-07-13 14:05:42

标签: angular rxjs subscribe

我编写了后端,所以我确切地知道从我的控制器返回的数据 (DTO) 的格式。 当我执行以下帖子时:

host=10.2.0.8 dbname=... user=... password=...

如果尝试指定响应:例如 UserDto,则会出现错误:

enter image description here

我还尝试将响应转换为 UserDto 类型的另一个变量,但也失败了。我不记得以前有这个问题(比如早期的 Angular 版本??)。

这必须很简单 - 我很抱歉不明白如何去做。 仅供参考:ng 12.1.1 版

提前致谢。 查克

2 个答案:

答案 0 :(得分:1)

subscribe() 方法返回一个你不能等待的 RxJS Subscription 对象的实例。您只能等待 Promise,因此您需要将 Observable 转换为 Promise:

await response = await this.http.post(this.baseUrl + 'account/login', dto).toPromise();

请注意,在 RxJS 8 中 toPromise() 将被两个方法 firstValueFrom()lastValueFrom() 替换。

答案 1 :(得分:1)

通过使用 post 方法的非通用形式,您将获得 Observable<HttpResponse> 的响应类型。因此,除非您自己管道和映射响应,否则订阅中的响应将是 HttpResponse 类型,因此您必须从 HttpResponse 获取正文。

this.http.post(this.baseUrl + 'account/login', dto).subscribe(
  (response: HttpResponse) => {
    const userDto: UserDto = response.body as UserDto
  }
);

或者,您可以使用 post 方法的通用形式,该方法将接受一个类型以映射到...

this.http.post<UserDto>(this.baseUrl + 'account/login', dto).subscribe(
  (response: UserDto) => {
    // The response is already map and typed to your UserDto.
  }
);
<块引用>

https://angular.io/api/common/http/HttpResponse

<块引用>

https://angular.io/api/common/http/HttpClient#post