json - 将来自 JSON 的 HTTP 响应转换为未按预期运行的接口
问题描述
我正在从角度客户端向服务器发出获取请求。我在其中进行调用的服务需要返回一个带有对象数组的可观察对象。问题是打字稿似乎不允许我将 JSON 转换为我的界面。
这是服务器作为响应发送的 JSON 对象:
export interface Message {
title: string;
body: string;
}
这是我想将身体投射到的界面。正文应该包含这些对象的数组:
export interface ICommonGameCard {
id: string;
pov: POVType;
title: string;
image_pair?: ICommonImagePair;
best_time_solo: number[];
best_time_online: number[];
}
export enum POVType{Simple, Free};
这是发出请求的服务:
public getGameCards(povType: POVType): Observable<ICommonGameCard[]> {
return this.http.get<ICommonGameCard[]>(this.BASE_URL + this.GET_ALL_CARDS_URL)
.pipe(
map((res: Response) => return <ICommonGameCard>res.json().body),
catchError(this.handleError<Message>("getUsernameValidation")),
);
}
显然,这是行不通的。我正在尝试将响应的 JSON 转换为消息接口,然后访问消息的接口主体,其中有一个 ICommonGameCard 数组。
我收到此错误:
[ts]
Argument of type 'OperatorFunction<Response, ICommonGameCard>' is not assignable to parameter of type 'OperatorFunction<ICommonGameCard[], ICommonGameCard>'.
Type 'Response' is missing the following properties from type 'ICommonGameCard[]': length, pop, push, concat, and 26 more. [2345]
我的语法到底有什么问题?
解决方案
export interface Message {
title: string;
body: ICommonGameCard[];
}
public getGameCards(povType: POVType): Observable<ICommonGameCard[]> {
return this.http.get<Message>(this.BASE_URL + this.GET_ALL_CARDS_URL)
.pipe(
map((message: Message) => message.body),
catchError(this.handleError<Message>("getUsernameValidation"))
);
}
推荐阅读
- scala - Spark - Add a column which sums another column, grouped by a third column, without losing other columns
- c# - 如何将combobox1项目从form1传递到form2中的combobox2
- c# - CommandLineParser:获取互斥选项集的名称
- android-studio - 让 Android 模拟器在 Ubuntu 20.04 上保持领先
- javascript - 我可以在 ScrollTrigger 中使用跨度而不是 div 吗?
- python - 如何根据导入的嵌套 json 改进删除 pandas df 列名前缀?
- javascript - 错误的 _.merge() 结果
- c# - 在 DDL 执行期间修改了 SqlTableDependency 引用的实体“INSERTED”
- python - 如何将 Ipyleaflet 映射添加到 PyQt5 应用程序?
- python - 如何在同一列Pyspark中获取星期几和数字