Angular2 *ngFor:"Cannot read property '0' of undefined"

Angular2 *ngFor: "Cannot read property '0' of undefined"

我试图从 JSON 文件中获取数据以构建表单。

这是我的模板的一部分:

  <div class="form-group">
    <label for="power">Power</label>
    <select class="form-control" id="power" required>
      <option *ngFor="let p of heroes" [value]="p.level">{{p.level}}</option>
    </select>
  </div>

这是远程 JSON 文件的一部分:

{
    "data": [
        {
            "level": "newbie",
            "places": [
                {
                    "place": "earth",
                    "categories": [
                        {
                            "category": "human",
                            "values": [
                                ...

它没有问题,我在 select 菜单中得到 newbie 和其他选项。 但是我想在地方循环,所以我以这种方式编辑 html 模板:

  <div class="form-group">
    <label for="power">Power</label>
    <select class="form-control" id="power" required>
      <option *ngFor="let p of heroes[0].places" [value]="p.place">{{p.place}}</option>
    </select>
  </div>

这是我用来从 JSON 文件中获取数据的服务:

@Injectable()
export class HeroService {
    private url = 'app/mockups/heroes.json';

    constructor(private http: Http) { }

    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.url)
            .toPromise()
            .then(response => response.json().data as Hero[])
            .catch();
    }
}

这里是 hero.component:

export class HeroComponent implements OnInit {
    heroes: Hero[];

    constructor(private heroService: HeroService) { }

    ngOnInit():void {
        this.getHeroes();
}

    getHeroes(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

但我收到 "Cannot read property '0' of undefined" 错误。

为什么?

我猜你想要的是

*ngFor="let p of heroes?.data"

因为heroes好像是一个对象,而ngFor只能迭代数组。 level 属性 也在数组项中。

替代@Gunter Zochbauer 的解决方案,您可以将 heroes 声明为合适类型的数组 属性。如果您有任何 class 具有 heroes 的所有属性,您将 heroes 属性 声明为:

heroes:Array<Heroes> //Assuming class name is Heroes

并在构造函数中初始化如下:

constructor(){
...    
this.heroes=new Array<Heroes>();
}

并且在您的 ngFor 循环中,只需按如下方式访问 class 属性:

<option *ngFor="let p of heroes" [value]="p.place">{{p.place}}</option>

希望对您有所帮助。

我想通了。我收到此错误是因为我正在异步获取数据,当 Angular 尝试解析绑定时,第一次数据仍然为空,因此 heroes[0] 失败。

所以我解决了初始化 heroes 数组并使用 "Elvis operator":

的问题

heroes: Hero[]; 而不是组件中的 heroes: Hero[] = [];

heroes[0]?.places 而不是 html 模板中的 heroes[0].places