2

I have data in firebase, I would like to display them using a loop.

    items: any;

    constructor(db: AngularFireDatabase) {
        db.list(`/users/`).snapshotChanges()
            .subscribe(o => { this.items = o; console.log(o) });
    }

    <div *ngFor="let item of items;">
        Items: {{item.key}}
        <p *ngFor="let device of item;">{{device.name}}</p>
    </div>

I can't display the second loop, NgFor only supports binding to Iterables such as Arrays. How to convert it?

1 Answer 1

1

In firebase, retrieving data via snapshotChanges() includes metadata with actual data in form of {key, payload, prevKey, type}.

In user case, you are trying to access item.name, but it is undefined.

You have to extract the payload before iterating. You can try something like this.

items$: any;

    constructor(db: AngularFireDatabase) {
        this.items$ = db.list(`/users/`).snapshotChanges()
            .pipe(map(changes => changes.map(c => ({
                key: c.key,
                payload: c.payload.val(),
                type: c.type,
                prevKey: c.prevKey
            }))));
    }

    <div *ngFor="let item of items$ | async;">
        Items: {{item.key}}
        name: {{item.payload.name}}
    </div>

If you don't need key, use valueChanges() instead of snapshotChanges().

For more details https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.