繁体   English   中英

Angular2 * ngFor:“无法读取未定义的属性'0'”

[英]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);
  }

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

为什么?

我猜你想要的是什么

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

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

我解决了这个问题。 我收到此错误是因为我异步获取数据,当Angular尝试解析绑定时,第一次数据仍然为null因此heroes[0]失败。

所以我解决了初始化heroes数组并使用“Elvis运算符”的问题:

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

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

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

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

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

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

在你的ngFor循环中,只需访问类属性,如下所示:

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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM