You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用Typescript动态接口获取游戏API数据的问题

问题根源

你定义的GamesByPlatform是键为平台枚举字符串、值为对应游戏数据容器的对象,并非数组,所以用results[0]这类数字索引访问自然返回undefined。你当前请求参数固定为ps4,接口返回的results对象的顶层唯一键就是ps4,你需要从该键下提取data属性里的游戏数组。

硬编码场景直接修复(当前测试用)

直接修改首页组件的订阅逻辑即可:

ngOnInit(): void {
  this.gameService.getGameList()
    .subscribe((results: GamesByPlatform) => {
      // 从ps4键下取游戏数组
      this.games = results['ps4'].data
    })
}

动态平台场景优化方案

如果后续要支持用户切换平台查询,可对服务和组件逻辑做如下改造:

  1. 改造游戏服务方法,接收平台作为入参:
import { Platforms } from '../shared/models/Game'; // 引入你定义的平台枚举

getGameList(platform: Platforms): Observable<GamesByPlatform> {
    let params = new HttpParams().set('platform', platform)
      .set('count', '16');

    return this.http.get<GamesByPlatform>(`${env.BASE_URL}`, {
      params: params
    });
}
  1. 组件调用时传入目标平台,用变量作为键取值:
ngOnInit(): void {
  // 该值后续可替换为用户选择的平台
  const targetPlatform: Platforms = 'ps4';
  this.gameService.getGameList(targetPlatform)
    .subscribe((results: GamesByPlatform) => {
      this.games = results[targetPlatform].data;
    })
}

类型适配优化

你当前的GamesByPlatform类型要求必须包含所有平台的键,但实际接口每次仅返回请求的单个平台键,为避免Typescript可能的空值提示,可调整类型定义为可选键:

export type GamesByPlatform = {
    // 加问号将所有平台键设为可选
    [key in Platforms]?: {
        data: Game[];
    }
}

取值时增加可选链和空值兜底,进一步提升代码健壮性:

this.games = results[targetPlatform]?.data ?? [];

内容的提问来源于stack exchange,提问作者ACDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:39:03