加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:06:10 所属栏目:安全 来源:网络整理
导读:我试图从 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 /di
我试图从 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属性也在数组项中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读