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

Angular TypeScript项目往数组push数据报无法读取undefined属性如何解决

问题原因

你遇到的报错本质是this指向丢失:你在fetch的回调中使用了普通function () {}声明,普通函数的this会根据调用上下文动态绑定,在异步回调场景下这里的this不会指向Angular组件实例,而是undefined,所以读取this.pokemonArray就会抛出属性读取错误。

同时你还有个类型定义问题:你把pokemonArray声明为Array<string>字符串数组,但实际要存入的是宝可梦对象,类型不匹配,也会导致TS编译报错。

解决方法

把所有回调的普通函数替换为箭头函数,箭头函数不会创建自己的this,会继承外层作用域的this(也就是你的组件实例),同时修正数组类型即可。

修正后的完整代码:

import { Component, OnInit } from "@angular/core";
import { PokemonConvPipe } from "../app/pipes/pokemon-conv.pipe";

// 可以自定义宝可梦类型,规范类型校验
interface Pokemon {
  name: string;
  id: number;
  sprites: {
    front_default: string;
  };
  // 其他你需要用到的属性
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
  // 修正数组类型,用自定义的Pokemon类型或者any
  pokemonArray: Array<Pokemon> = [];
  constructor() {}

  ngOnInit() {
    this.fetchPokemonList();
  }
  fetchPokemonList() {
    fetch("https://pokeapi.co/api/v2/pokemon?limit=20&offset=0")
      .then((response) => response.json())
      // 这里改成箭头函数
      .then((allpokemon) => {
        allpokemon.results.forEach((pokemon) => {
          let url = pokemon.url;
          fetch(url)
            .then((response) => response.json())
            // 这里改成箭头函数
            .then((pokeData) => {
              console.log("pokeData", pokeData);
              if (pokeData) {
                this.pokemonArray.push(pokeData);
              }
            });
        });
      });
  }
}

优化建议

如果是Angular项目更推荐使用官方的HttpClient替代原生fetch,可以更好的和Angular的变更检测、异步管道配合,多个并行请求也可以用Promise.all统一处理,避免回调嵌套。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:09:02