2016-11-23 73 views
-1

我有一個 'nvi.json' 文件:Anglar2 ngFor不能循環

[ 
{ 
"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> 

控制檯:

例外:錯誤./BookPage類BookPage - 聯模板:33:5所造成的:無法找到一個不同的支持對象「 [對象]類型的[對象對象]。 NgFor僅支持與陣列等Iterables綁定。

+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? '* ngFor'只能迭代數組。 '章節[0]'返回一個對象,這就是你得到錯誤的原因。如果你刪除'[0]'它可能工作。 –

回答

2

嗨,你不能用*ngFor循環一個對象。 你必須重新格式化你的json來獲得一個數組而不是一個文字對象。

你可以做這樣的事情:

[ 
    { 
     "abbrev": "gn", 
     "book": "Gênesis", 
     "chapters": [ 
      { 
       "id": 1, 
       "verses": [ 
        { 
         "id": "1", 
         "...": "...", 
        } 
       } 
      }, 
      { 
       "id": 2, 
       "verses": [ 
        { 
         "id": "1", 
         "...": "...", 
        } 
       } 
      } 
     ] 
    } 
] 

<div *ngFor="let chapter of chapters"> 
    {{chapter.id}} 
    <div *ngFor="let verse of chapter.verses"> 
     {{verse.id}} 
    </div> 
</div>