AngularFire2:实时数据库:如何获取键和值 [英] AngularFire2: Realtime Database: how to get key and value
问题描述
我使用AngularFire2从Firebase数据库实时获取数据.
I use AngularFire2 to get data from Firebase Database (realtime).
我做了什么:
- Firebase数据库
{ 班级" : { 学生" : { 汤姆":男", 玛丽":女性", 彼得":男", 劳拉":女" }, "numberOfStudent":10 } }
{ "class" : { "student" : { "Tom" : "male", "Mary" : "female", "Peter" : "male", "Laura" : "female" }, "numberOfStudent" : 10 } }
-
app.component.ts
app.component.ts
import { AngularFireDatabase } from 'angularfire2/database'; import { Observable } from 'rxjs/Observable'; ... export class AppComponent { class: Observable<any>; students: Observable<any[]>; constructor(private db: AngularFireDatabase) { this.class = db.object(‘class’).valueChanges(); this.students = db.list(‘class/student’).snapshotChanges(); } }
-
app.component.html:
app.component.html:
<h2>Class size: {{ (class | async)?.numberOfStudent }}</h2> <ul> <li *ngFor="let i of students | async"> {{i.key}} : {{i.value}} </li> </ul>
发生了什么事
班级人数:10
Class size: 10
汤姆:
玛丽:
彼得:
劳拉:
它不返回list的值.
It doesn't return the value of list.
任何建议都值得赞赏.
推荐答案
UPD
使用新的 Angular 6 和 RxJS 6 ,您将执行以下操作:
with new Angular 6 and RxJS 6 you'll do this:
import { map } from 'rxjs/operators'; // ... return this.fb.list(`/path/to/list`) .snapshotChanges() .pipe(map(items => { . // <== new way of chaining return items.map(a => { const data = a.payload.val(); const key = a.payload.key; return {key, data}; // or {key, ...data} in case data is Obj }); }));
这篇关于AngularFire2:实时数据库:如何获取键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!