我尝试从 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": [
...
它工作没有问题,我明白了newbie
以及其他选择select
菜单。
但我想在一些地方循环,所以我用这种方式编辑 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>
这是我用来从 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();
}
}
这是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’” error.
Why?