如何使用 angular 从 firebase 检索嵌套在两个集合中的数据

how to retrieve data nested in two collections from firebase with angular

我是 Angular - Firebase 开发的新手,我无法理解如何检索嵌套在两个集合中的数据。 我有一个名为 "Orders" 的集合,其中包含一个字段调用 "auth",它是用户 ID,我还有另一个集合 "User Profile",它的 $id 是"auth"。在用户配置文件中,我有一个名为 roomNumber 的字段,它是我每次阅读时都想在订单的 ng-repeat 中检索的内容。

在我看来,我正在尝试做这样的事情:

<tr ng-repeat="item in items | filter: searchKeyword ">
  <td align="left">{{item.$id}} -  {{roomNumber(item.$id)}}</td></tr>

roomNumber 是我控制器中的一个函数

$scope.roomNumber = function(id) {
 var rootRef = new Firebase("https://xxxx-fire-yyyy.firebaseio.com/userProfile"+ '/' + id);
  $scope.userdet = $firebaseArray(rootRef);
  rootRef.on("value", function(rootSnapshot) {
        var key = rootSnapshot.key();
        var childKey = rootSnapshot.child("room").val();
        console.log("room ", childKey)
    });
 return childKey
  }

当我 运行 此代码并在我的 js 控制台中查看结果时,发生了奇怪的事情: 1. 重复很多次 2. 永远获取不到childKey值

我一直在阅读 Firebase 文档,但我真的不明白该怎么做"silly",有人能告诉我怎么做吗?

要解决 childKey 无法读取的问题,您需要使用此方法:

var childKey = rootSnapshot.val().room;

而不是这个:

var childKey = rootSnapshot.child("room").val();
console.log("room ", childKey)

参考:https://www.firebase.com/docs/web/guide/retrieving-data.html

当您将函数绑定到 $scope 并在 html 中调用它时,它希望在调用时立即得到答复。因此,当您查询 firebase 时,它​​花了不少时间让您返回答案,angularjs 已经从函数中得到了未定义的答案。

所以发生的事情是,当您向 rootRef.on 提供函数时,您正在注册一个回调,然后在您注册回调后立即返回 childKey 的值。不幸的是,childKey 仅由回调函数设置(firebase 尚未执行)。因此 angularjs 从您的 roomNumber 函数中得到未定义的答案。

为了完成这项工作,您必须事先获得房间号,然后可能将它们添加到 $scope.items 中的每个项目中,然后使用

<td align="left">{{item.$id}} -  {{item.room}}</td></tr>

而不是

<td align="left">{{item.$id}} -  {{roomNumber(item.$id)}}</td></tr>

要加载所有房间号,您可以在 $scope.items 加载后调用类似这样的函数

for (var i = 0; i < $scope.items.length; i++) {
    var rootRef = new Firebase("https://xxxx-fire-yyyy.firebaseio.com/userProfile"+ '/' + $scope.items[i].$id);
    $scope.userdet = $firebaseArray(rootRef);
    rootRef.on("value", function(rootSnapshot) {
        var key = rootSnapshot.key();
        var childKey = rootSnapshot.val().room;
        $scope.items[i].room = childKey;
    });
}

它将更改每个项目以引用房间。不幸的是,该列表不会随着数据更新而更新,因此更好的解决方案是在从服务器获取项目的任何函数中执行相同的查询,并在将房间添加到项目列表时将房间添加到每个项目.