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

编程入门 行业动态 更新时间:2024-10-26 06:36:06
本文介绍了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(); } }

这是heroponent:

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'";

本文发布于:2023-11-22 23:19:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   未定义   ngFor   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!