我有'nvi.json'文件:
[
{
"abbrev": "gn",
"book": "Gênesis",
"chapters": [
{
"1": {
"1": "...",
"2": "..."
}
},
{
"2": {
"1": "...",
"2": "..."
}
},
{
"3": {
"1": "...",
"2": "..."
}
}
]
}
]
我正在这样访问:
export class BookPage {
public chapters: Array<string>;
private url: any = "../../assets/nvi.json";
constructor(public navCtrl: NavController, private NavParams: NavParams, public http: Http) {
let id = NavParams.get('id');
this.http.get(this.url).map(res => res.json())
.subscribe(data => {
this.chapters = data[id].chapters[0];
console.log(this.chapters);
});
}
'this.chapters'包含第一章,其中包含经文。
但我无法循环这些经文
<div *ngFor="let item of chapters">
{{item}}
</div>
控制台:
EXCEPTION:./BookPage类中的错误BookPage - 内联模板:33:5引起:找不到类型为'object'的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如Arrays。
答案 0 :(得分:2)
您好,您无法使用*ngFor
循环对象。
你必须重新格式化你的json以拥有一个数组,而不是一个文字对象。
你可以这样做:
[
{
"abbrev": "gn",
"book": "Gênesis",
"chapters": [
{
"id": 1,
"verses": [
{
"id": "1",
"...": "...",
}
}
},
{
"id": 2,
"verses": [
{
"id": "1",
"...": "...",
}
}
}
]
}
]
javascript
export class BookPage {
public chapters:Array<string>;
private url:any = "../../assets/nvi.json";
constructor(public navCtrl:NavController, private NavParams:NavParams, public http:Http) {
let id = NavParams.get('id');
this.http.get(this.url).map(res => res.json())
.subscribe(data => {
this.chapters = data[id].chapters; // remove the [0] or store directly the verses by accessing the verses property
console.log(this.chapters);
});
}
}
html
<div *ngFor="let chapter of chapters">
{{chapter.id}}
<div *ngFor="let verse of chapter.verses">
{{verse.id}}
</div>
</div>