Angular2 ngFor help with loop

Asked

Viewed 981 times

3

I have a file nvi.json that is this way:

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

And I’m accessing it like this:

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 containing the verses, but I’m not getting a loop of these verses.

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

Console:

EXCEPTION: Error in ./BookPage class BookPage - inline template:33:5 caused by: Cannot find a differ supporting object '[object Object]' of type 'object'.      NgFor only supports binding to Iterables such as Arrays.
  • *ngFor="Let item of Chapters"

  • Thanks for the remark! I posted via mobile and with it many typos.

  • The Chapters are organized in a way that the angular cannot read ["1":{Object}, "2":{Object}] you need to leave an Objects [{Object},{Object array}]

  • from { "1": { "1": "...", "2": "..." } } would be better to send from backend { "1": [{Chapter:1, .... } , {Chapter:2, .... }] }

2 answers

1

If you cannot work with the structure of this JSON to transform it into an array, use the Angular keyvalue pipe: https://angular.io/api/common/KeyValuePipe

<div *ngFor="let item of chapters | keyvalue">
    {{item.key}}:{{item.value}}
</div>

1

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

See 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 Chapters at least it should go through a process like this:

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

and one more thing does not help you define the type of variable and then set a value of different type what will prevail will be the last set type.

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

In doing so chapters will become an object not an array. make a console.log(chapters); and observe this object well in the console, with the real data will be easier you see the behavior.

I hope I’ve helped.

A Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.