My goal is to connect to Firebase
, retrieve data from a specified location, loop through the fetched data using snapshot.val()
and build an Array
. Then I plan to return this Array
and loop through it in component.html
to create a Dropdown
.
I am currently struggling with the syntax for implementing such a service method. Below is my existing code that is called from ngOnInit()
in app.component.ts
:
getExerciseOptions(): Array<Exercise> {
const items: Exercise[] = [];
this.exerciseDbRef2.on("value", (snapshot) => {
snapshot.forEach((snap) => {
items.push({
id: snap.key,
description: snap.val().description
});
return false;
});
});
}
The reference this.exerciseDbRef2
points to the Firebase table as defined below:
private exerciseDbRef2 = this.fire.database.ref('/exercise_description');
The error message I am encountering states:
A function whose declared type is neither 'void' nor 'any' must return a value.
When I change return false
to return items
, I receive the following new error:
Argument of type '(snap: DataSnapshot) => Exercise[]' is not assignable to parameter of type '(a: DataSnapshot) => boolean'.
Type 'Exercise[]' is not assignable to type 'boolean'.
I have considered using child_added
, but I believe this event would trigger every time a new child is added to the location, which is not the behavior I desire. The children within this location will remain constant without any additions. Perhaps I misunderstood the purpose of 'child_added'?
As I am relatively new to utilizing Firebase, I appreciate your patience as I navigate the learning curve. If you identify any flaws in my current approach, please feel free to point them out.
In summary: Connect to Firebase
, fetch all children from the specified location (i.e., exercise_description table), iterate through the snapshot
, construct an Array
, and return it.
Subsequently, within the component, loop through the Array
to generate the Dropdown
.
Could someone kindly provide guidance on how to effectively return the Array
based on the data obtained from snapshot.val()
?