使用 AngularFire 查找/加入数据

Look up / join data with AngularFire

我有一个问题,关于如何在前端显示数据之前合并来自不同 Firebase 数据库节点的数据。我有一个具有以下结构的 Firebase 数据库。 (我是 nosql 设置的新手,所以这看起来更相关):

{
  "agents" : {
    "-KPCmnwzjd8CeSdrU3As" : {
    "contactNumber" : "12345",
    "name" : "aaa"
    },
    "-KPCmw6dKuopDlsMVOlU" : {
     "contactNumber" : "123",
     "name" : "bbb"
    },
    "-KPCoWcLecpchcFV-vh_" : {
     "contactNumber" : "123",
     "name" : "ccc"
    },
    "-KPROMhPatLjVxMdvfLf" : {
     "contactNumber" : "256342",
     "name" : "blah"
    },
    "-KPWIFl5qp5FvAeC3YhG" : {
     "contactNumber" : "123",
     "name" : "eee"
    }
  },
  "listings" : {
    "-KPWKTvW3GzFEIT2hUNU" : {
      "agent" : "-KPCoWcLecpchcFV-vh_",
      "description" : "third",
      "reference" : "REF1"
    }
  }
}

我正在使用 Firebase SDK 3.2.0 和 AngularFire 2.0.1。在我的 Angular 应用程序中,我可以获取房源列表,并针对每个房源查找代理信息。我没有将代理信息与列表一起存储的原因是我希望能够更新代理并且更改应该反映在所有列表中。如果代理电话号码发生变化(例如),我不想去更新所有列表。

在我的控制器中,我有以下内容:

// get the listings
var listingsRef = firebase.database().ref().child('listings');
vm.listings = $firebaseArray(listingsRef);

// this will move to my ui-router as a resolve but for simplicity's sake
// I added it here...
vm.listings.$loaded().then(function(data){
  // loop through the listings...
  data.forEach(function(listing) {
    if (listing.agent) {
      // get the agent for the listing 
      listing.agent = AgentFactory.getAgent(listing.agent);
    }
  });
});

现在数据在前端正确显示。由于需要解析 getAgent 承诺,因此代理数据显示略有延迟。

我的问题是: 这是获取代理数据的正确方法吗?我应该遍历列表并为每个查询代理数据吗?我如何等待/跟踪所有要解决的 getAgents?

如有任何帮助,我们将不胜感激。

谢谢。

我以类似的方式构建了我的数据。如果你想等待所有 getAgents 解决你可以使用 $q.all。我不完全确定你的 AgentFactory.getAgent 返回了什么,但我们假设它是 $firebaseObject。如果是这种情况,请注入 $q 然后执行以下操作:

vm.listings.$loaded().then(function (data) {
    // loop through the listings...
    var promises = [];
    data.forEach(function (listing) {
        if (listing.agent) {
            // get the agent for the listing
            listing.agent = AgentFactory.getAgent(listing.agent);
            promises.push(listing.agent.$loaded());
        }
    });
    return $q.all(promises);
}).then(function (agents) {
    //all agents are loaded
});