我试图从
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": [ ...
它没有问题,我在选择菜单中获得新手和其他选择.
但我想在地方循环,所以我用这种方式编辑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>
@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); }
为什么?
解决方法
我猜你想要的是什么
*ngFor="let p of heroes?.data"
因为英雄似乎是一个对象,而ngFor只能迭代数组.level属性也在数组项中.