5

I trying to get data from a JSON file to build a form.

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:

{
    "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. But i want to loop on places, so i edit the html template in this way:

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

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

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.

Why?

4

3 回答 3

14

我猜你想要的是

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

因为heroes似乎是一个对象,并且ngFor只能迭代数组。该level属性也位于数组项中。

于 2016-09-06T08:23:07.187 回答
5

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

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

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

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

于 2016-09-06T16:17:24.910 回答
1

替代@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>

希望能帮助到你。

于 2016-09-06T08:35:02.250 回答