首页 > 解决方案 > 如何循环显示来自firebase的数据

问题描述

我在 firebase 中有数据,我想使用循环显示它们。

    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>

我无法显示第二个循环,NgFor 只支持绑定到 Iterables,例如 Arrays。如何转换它?

标签: firebase-realtime-databaseangularfire2

解决方案


在 firebase 中,通过 snapshotChanges() 检索数据包括具有 {key, payload, prevKey, type} 形式的实际数据的元数据。

在用户案例中,您正在尝试访问item.name,但它是未定义的。

您必须在迭代之前提取有效负载。你可以尝试这样的事情。

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>

如果您不需要key,请使用 valueChanges() 而不是 snapshotChanges()。

有关更多详细信息https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md


推荐阅读