【问题标题】:Casting an HTTP response from JSON to interface not behaving as expected将来自 JSON 的 HTTP 响应转换为未按预期运行的接口
【发布时间】:2019-06-27 01:52:32
【问题描述】:

我正在从 Angular 客户端向服务器发出 get 请求。我在其中进行调用的服务需要返回一个带有对象数组的可观察对象。问题是打字稿似乎不允许我将 JSON 转换为我的界面。

这是服务器作为响应发送的 JSON 对象:

export interface Message {
    title: string;
    body: string;
}

这是我想将 body 投射到的界面。正文应该包含这些对象的数组:

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]

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

【问题讨论】:

标签: json angular typescript http


【解决方案1】:
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"))
      );
}

【讨论】:

  • 感谢您的回复,但这真的有用吗?响应应该是 Message 接口,并且 ICommonGameCard 的数组在消息的“body”字段中。根据我从您共享的代码中看到的情况,这会尝试将“title”和“body”字段都转换为 ICommonGameCard 数组,但这是行不通的。
猜你喜欢
  • 2017-09-13
  • 1970-01-01
  • 2022-01-22
  • 2019-12-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多