【发布时间】:2017-06-04 20:16:20
【问题描述】:
我正在连接到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”?
我对@987654338@ 还很陌生,所以我刚开始学习,所以请随意,我还想提一下,如果我目前这样做的方式不正确,请带上它引起我的注意。
所以为了澄清:连接到Firebase,从给定位置检索所有孩子,即练习描述表,循环通过snapshot,构建一个Array并返回它。
然后在组件上循环通过Array 并构建Dropdown。
有人可以解释一下我如何根据snapshot.val() 返回Array 吗?
【问题讨论】:
-
那个 sn-p 看起来不完整。你有切碎的碎片吗?该错误意味着
on回调正在返回一个数组。而getExerciseOptions函数被声明为返回Array<Exercise>,但什么也不返回。 -
@cartant 感谢您提前提供帮助,sn-p 正确。我对如何返回使用从
Firebase返回的值构建的数组的语法感到困惑。理想情况下,我想从此函数返回Array<Exercise>
标签: arrays angular typescript firebase firebase-realtime-database