首页 > 解决方案 > 将来自 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]

我的语法到底有什么问题?

标签: jsonangulartypescripthttp

解决方案


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

推荐阅读