【发布时间】:2020-07-13 13:04:28
【问题描述】:
我正在尝试使用 Firebase 的实时数据库,并且我已经为这样的书籍列表及其价格创建了一个 API。
{
"Books":[
{"Angular 4": "$9.99"},
{"HTML 5": "$10.99"},
{"CSS3": "$21.90"}
]
}
在 npm 中从 angularfire2 包中导入 AngularFirebase 所需的所有依赖项后,我编写了以下代码来从数据库中检索值:
booklists: AngularFireList<any[]>;
booklistCollection: Observable<any[]>;
constructor(public angularFireDatabase: AngularFireDatabase) {
this.booklists = angularFireDatabase.list('/Books');
this.booklistCollection = this.booklists.snapshotChanges();
}
在 app.component.html 中,我编写了以下代码来遍历 observables。
<div>
<ul>
<li *ngFor="let booklist of booklistCollection | async">
{{ booklist.key }} : {{ booklist.value }}
</li>
</ul>
</div>
但是,输出只包含键而不是值。
我无法找到一种同时获取键和值的方法。我知道可以使用 AngularFirebaseList 的 valueChanges() 方法单独获取值,但我需要一种一次性获取键和值的方法。
【问题讨论】:
-
即使没有用于保存数据的 snapshotChanges() 也应该可以工作。您是否将标题打印为键或 Firebase 键?您能否在 Firebase 中显示输出,以及您的数据的仪表板视图?
-
这种数据结构只有在我使用 snapshots.forEach(childSnapshot => { key = Object.keys(childSnapshot)[0]; val = childSnapshot[key]; }) 时才有效;也许你可以试试 booklist[booklist.key] 的价值。
标签: angular firebase firebase-realtime-database angularfire