简体   繁体   English

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

[英]Angular2 *ngFor: “Cannot read property '0' of undefined”

I trying to get data from a JSON file to build a form. 我试图从JSON文件中获取数据来构建表单。

Here is a portion of my template: 这是我模板的一部分:

  <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>

Here is part of the remote JSON file: 这是远程JSON文件的一部分:

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

It works with no problem and i get newbie and other choices in the select menu. 它没有问题,我在select菜单中获得newbie和其他选择。 But i want to loop on places, so i edit the html template in this way: 但我想在地方循环,所以我用这种方式编辑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>

Here is the service that i use to grab data from JSON file: 这是我用来从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();
    }
}

and here is the hero.component : 这是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);
  }

But i get "Cannot read property '0' of undefined" error. 但我得到“无法读取属性'0'未定义”错误。

Why? 为什么?

I guess what you want is 我猜你想要的是什么

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

because heroes seems to be an object, and ngFor can only iterate array. 因为heroes似乎是一个对象,而ngFor只能迭代数组。 The level property also is in an array item. level属性也在数组项中。

I figured out the problem. 我解决了这个问题。 I got this error because I'm fetching data asynchronously and when Angular tries to resolve bindings the first time data is still null therefore heroes[0] fails. 我收到此错误是因为我异步获取数据,当Angular尝试解析绑定时,第一次数据仍然为null因此heroes[0]失败。

So I solved the problem initializing heroes array and using the "Elvis operator": 所以我解决了初始化heroes数组并使用“Elvis运算符”的问题:

heroes: Hero[]; instead of heroes: Hero[] = []; 而不是heroes: Hero[] = []; in the component. 在组件中。

heroes[0]?.places instead of heroes[0].places in the html template. heroes[0]?.places而不是heroes[0].places 。在html模板中heroes[0].places

Alternative to @Gunter Zochbauer's solution, you can declare heroes as Array property of suitable type. 作为@Gunter Zochbauer解决方案的替代方案,您可以将heroes声明为合适类型的Array属性。 If you have any class with all attributes of heroes you declare heroes property as: 如果你有任何具有heroes属性的类,你将heroes属性声明为:

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

And initialize it in constructor as follows: 并在构造函数中初始化它如下:

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

And in your ngFor loop simply access class attributes as follows: 在你的ngFor循环中,只需访问类属性,如下所示:

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

Hope it helps. 希望能帮助到你。

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

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