数组 – Angular2 * ngFor:“无法读取未定义的属性’0’”

前端之家收集整理的这篇文章主要介绍了数组 – Angular2 * ngFor:“无法读取未定义的属性’0’”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从 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": [
                                ...

它没有问题,我在选择菜单中获得新手和其他选择.
但我想在地方循环,所以我用这种方式编辑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);
  }

但我得到“无法读取属性’0’未定义”错误.

为什么?

解决方法

我猜你想要的是什么

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

因为英雄似乎是一个对象,而ngFor只能迭代数组.level属性也在数组项中.

猜你在找的Angularjs相关文章