我连接到Firebase
并从给定位置检索数据,我想要做的是遍历snapshot.val()
构建和Array
,通过它返回Array
,然后循环的component.html
并建立一个Dropdown
。返回数组
目前我有困难搞清楚这种服务方法的语法,这是我目前的代码。 - 这是从app.component.ts
内ngOnInit()
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;
});
});
}
所以this.exerciseDbRef2
点内Firebase
表名为如下所示:
private exerciseDbRef2 = this.fire.database.ref('/exercise_description');
目前我收到的错误是
A function whose declared type is neither 'void' nor 'any' must return a value.
哪我明白了,所以当我将return false
更改为return items
时,新的错误是:
Argument of type '(snap: DataSnapshot) => Exercise[]' is not assignable to parameter of type '(a: DataSnapshot) => boolean'.
Type 'Exercise[]' is not assignable to type 'boolean'.
我已经看过用child_added
但是从我的理解,这将被称为每当一个新的子项添加到该位置,这是不是我要找的时间。在这个位置的孩子不会改变,也不会被添加。 - 也许我错误地解释了'child_added'?
我对Firebase
比较陌生,所以我在学习曲线的开头,所以请裸露出来,我还想提一下,如果我目前这样做的方式不正确,请带上它我的注意力。
所以澄清:连接到Firebase
,通过snapshot
检索给定的位置即exercise_description表,循环中的所有儿童,建设Array
并将其返回。
然后在组件循环中通过Array
并构建Dropdown
。
有人可以请解释我如何去基于snapshot.val()
退回Array
?
该代码片段看起来并不完整。你把零碎切碎了吗?该错误意味着'on'回调正在返回一个数组。并且'getExerciseOptions'函数被声明为返回'Array',但不返回任何内容。 –
cartant
@cartant感谢您的帮助,它的正确代码片段。关于如何返回使用从Firebase返回的值构建的数组,我对这个语法感到困惑。理想情况下,我想从这个函数返回'Array' –