I use AngularFire2 to get data from Firebase Database (realtime).
What I have done:
{ “class” : { “student” : { “Tom” : “male”, “Mary” : “female”, “Peter” : “male”, “Laura” : “female” }, "numberOfStudent” : 10 } }
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:
<h2>Class size: {{ (class | async)?.numberOfStudent }}</h2>
<ul>
<li *ngFor="let i of students | async">
{{i.key}} : {{i.value}}
</li>
</ul>
What happened:
Class size: 10
Tom :
Mary :
Peter :
Laura :
It doesn't return the value of list.
Any suggestion is appreciated.
Firebase automatically creates API keys for your project when you do any of the following: Create a Firebase project > Browser key auto-created. Create a Firebase Apple App > iOS key auto-created. Create a Firebase Android App > Android key auto-created.
You can create a unique key in Firebase database using push() and then add child nodes under that key. Now next time when you come to that activity, first check if parent node exists or not. If the node exists, save parent node key and use it to save new child nodes.
UPD
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
});
}));
I managed to get the key and value of list. Just follow some tips below:
<li *ngFor="let i of seats | async">
{{i.key}} : {{i.payload.val()}}
</li>
It worked for me, but I am still opening to receive more best practices
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With