从 firebase 获取 child 并将其用作参考

Get a child from firebase and use it as a ref

刚开始学习 angular,但我一直在使用 jQuery 制作网站,现在开始开发一些与网站连接到相同 firebase 的应用程序。

我遇到的问题是我找不到获取 child 属性 并在 ref 中使用它的方法。我想在下面的示例中获取值“example”:

users: {
    simplelogin:1 {
        CurrentGroup : "example"
     }
  }

我通常用 jQuery 做的事情是这样的:

currentUserRef.on('value', function(snapshot){
    currentGroup = snapshot.val().CurrentGroup;
});

var checkCurrentGroup = setInterval (function(){
    if ( currentGroup !== undefined ) {
        clearInterval(checkCurrentGroup);
        var currentGroupUsersRef = new Firebase(FB + "/groupUsers/" + currentGroup);
        //Rest of the code for the page/app
 }}, 200);

那么,这在 Angular 中是如何完成的?我的尝试是复制 firebase 指南中的示例:

app.factory("Profile", ["$firebase", function($firebase) {
  return function(username) {
    var userRef = new Firebase(FB + "/users/" + username);
    return $firebase(userRef).$asObject();
  }
}]);


app.controller("ProfileCtrl", ["$scope", "Profile",
  function($scope, Profile) {
        console.log("profile = ", Profile(uid));
        console.log("profile current group = ", Profile(uid).CurrentGroup);
      }
]);

控制台日志:

profile = d {$$conf: Object, $id: "simplelogin:76", $priority: null, $save: function, $remove: function…}$$conf: Object$id: "simplelogin:76"$priority: nullCurrentGroup: "Big Group"displayName: "Jim"email: "someone@email.com"firstLogin: trueprovider: "password"provider_id: "simplelogin:76"proto: Object

profile current group = undefined

我可以 select 用户 object 但是当我这样做时 user.currentGroup 它将是未定义的。不知道我是否在正确的轨道上。

AngularFire 的 $asObject() returns 一个 $FirebaseObject, which your service in turn returns. I just noticed that the API documentation for $asObject() 状态:

Returns a synchronized object. When data is updated on the server, the local copy will be altered (but not replaced) to match.

不幸的是,这不是真的(或者充其量:容易被误解)。

Firebase 将数据从服务器加载(并同步)到您的客户端代码异步。由于数据(或更新的数据)可能需要相当长的时间才能返回,因此 AngularFire 的 $asObject() 而不是 returns 所谓的承诺:一种数据结构 在某个时刻future 将包含您请求的数据。很明显,当您访问 Profile(uid).CurrentGroup 时,数据尚未下载。

当您简单地将对象绑定到视图时,这大部分都不是问题,这在 AngularJS 中很常见。如果这样做,AngularFire 将在新(或更新)数据可用时自动通知 AngularJS,然后 AngularJS 将更新视图。魔法!

但是您的 console.log 声明不是这个魔法的一部分。因此,您需要自己处理承诺。幸运的是,这不是很困难而且很常见;如此常见,以至于我在上面引用的 "unintuitive at best" API 文档中包含如何执行此操作的示例:

var record = sync.$asObject();
record.$loaded().then(function() {
  console.log("record ID:", record.$id);
});

您应该能够很容易地为您的数据修改此代码段。但请记住:当您只是将对象绑定到 AngularJS 视图时,通常不需要 $loaded() 处理程序。在这种情况下,AngularFire 的三向数据绑定应该会自动工作。