Angular2 ngFor help with loop

1

I have a file 'nvi.json' which looks like this:

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

And I'm accessing this way:

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' returns the first chapter where it contains the verses.

But I'm not able to loop these verses.

<div *ngFor="let item of chapters">
 {{item}}
</div>

Console:

EXCEPTION: Error in ./BookPage class BookPage - inline template: 33: 5 caused by: Can not find a supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

    
asked by anonymous 22.11.2016 / 20:14

1 answer

0

So I could simulate your problem here in pure JavaScript, see json is an object or even though it looks like a nested array it is not in this format.

Here's how to transform an object into an array:

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

In case the object you are exposing at least chapters should go through a process like this:

var arr = Object.keys(chapters[1]).map(function (key) { return chapters[1][key]; });

And one more thing is not good for you to define the type of variable and then to set a value of different type that will prevail will be the last set type.

public chapters: Array<string>;
...
this.chapters = data[id].chapters[0];

When doing this, chapters will become an object, not an array. make a console.log(chapters); and observe this object well in the console, with the actual data it will be easier for you to see the behavior.

I hope I have helped.

A hug.

    
08.06.2017 / 03:50