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

Angular 14:如何正确获取训练师的Pokemons数组?

修正训练师Pokemons数组获取函数的方案

你的当前函数存在关键问题:API返回的不是单个Trainer对象,而是包含entrenadores数组的顶层对象,直接访问entrenador.pokemons会导致逻辑错误。

修正后的函数代码

getPokemonsOfATrainer(nombreEntrenador: string){
  // 调整类型断言匹配API返回结构
  return this.http.get<{ entrenadores: Trainer[] }>(`${this.apiUrl1}?fullName=${nombreEntrenador}`).pipe(
    map(response => {
      // 从训练师数组中定位目标条目
      const targetTrainer = response.entrenadores.find(trainer => trainer.fullName === nombreEntrenador);
      // 存在则返回其pokemons数组,否则返回空数组避免undefined
      return targetTrainer ? targetTrainer.pokemons : [];
    })
  );
}

核心修正说明

  1. 类型对齐:将get<Trainer>改为get<{ entrenadores: Trainer[] }>,让TypeScript识别API返回的真实结构。
  2. 数组筛选:通过find方法从entrenadores数组中找到匹配fullName的训练师。
  3. 空值防护:用三元运算符处理找不到训练师的情况,返回空数组避免后续逻辑报错。

额外补充建议

  • 确保Trainer及关联接口定义正确:
    interface Trainer {
      fullName: string;
      pokemons: Pokemon[];
    }
    
    interface Pokemon {
      name: string;
      nature: string;
      attacks: Attack[];
    }
    
    interface Attack {
      name: string;
      type: string;
      style: string;
    }
    
  • 如果API可能返回多个匹配的训练师,可改用filter+flatMap合并所有匹配结果:
    return response.entrenadores
      .filter(trainer => trainer.fullName === nombreEntrenador)
      .flatMap(trainer => trainer.pokemons);
    

内容的提问来源于stack exchange,提问作者Eric Díaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:15:37