2016-08-22 25 views
0

我對如何在前端顯示不同Firebase數據庫節點之前合併數據存在疑問。我有一個具有以下結構的Firebase數據庫。 (我是新來的一個NoSQL的設置,所以這看起來更關係):通過AngularFire查找/加入數據

{ 
    "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" 
    } 
    } 
} 

我使用火力地堡SDK 3.2.0和2.0.1 AngularFire。在我的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來解決?

任何幫助,將不勝感激。

謝謝。

回答

0

我的數據結構類似。如果您想等待所有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 
}); 
+0

感謝您的幫助。這很好。是的,getAgent調用返回一個firebaseObject。出於興趣,你認爲有這樣的查詢性能問題嗎?從我讀過的內容看,Firebase在內部進行了大量優化和緩存。 –

+0

不,從我的理解中應該會很好。 –