Angular2 * ngFor:“无法读取未定义的属性'0'"; [英] Angular2 *ngFor: "Cannot read property '0' of undefined"

查看:113
本文介绍了Angular2 * ngFor:“无法读取未定义的属性'0'";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从JSON文件中获取数据以构建表单.

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

这是我模板的一部分:

  <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文件的一部分:

Here is part of the remote JSON file:

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

它没有问题,我在select菜单中得到了newbie和其他选择. 但是我想在地方循环播放,所以我以这种方式编辑html模板:

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>

这是我用来从JSON文件中获取数据的服务:

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();
    }
}

这是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'" 错误.

为什么?

推荐答案

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

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.

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

So I solved the problem initializing heroes array and using the "Elvis operator":

heroes: Hero[];而不是组件中的heroes: Hero[] = [];.

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

heroes[0]?.places instead of heroes[0].places in the html template.

这篇关于Angular2 * ngFor:“无法读取未定义的属性'0'";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆