My Firebase Database has structure as follows:
fire-demo-123
Currently I am fetching list using this code
component.ts
title = 'FirebaseDemo';
// courses: any[];
courses$;
course$;
author$;
todos$: AngularFireList<any>;
// subscription : Subscription;
constructor(public db: AngularFireDatabase) {
db.list('/course')
.valueChanges()
.subscribe((inp) => {
this.courses$ = inp;
console.log(this.courses$);
// Output is ["course1", "course2", "course3", "course4"]
});
component.html
<h3>List</h3>
<ul>
<li *ngFor="let course of courses$">{{course}}
</li>
</ul>
But is there any way to get them with reference to id like {id:1,value:"course1"}...
Here's my database export.
{
"course" : {
"1" : "course1",
"2" : "course2",
"3" : "course3",
"-MZOnCn1YdQ2sGLhajuL" : "course4"
}
}
I am trying to get courses with id.
Keeping your database structure the same, best you can do is to loop over all the keys and create a new object as shown below:
const courses = {
"1": "course1",
"2": "course2",
"3": "course3",
"-MZOnCn1YdQ2sGLhajuL": "course4"
}
const res = []
Object.keys(courses).forEach((course) => {
res.push({id: course, value: courses[course]})
})
console.log(res);
I tried running the code above and worked for me.
Please make sure you replace the courses
object with the snapshot value from realtime database.