代码之家  ›  专栏  ›  技术社区  ›  Buzz.K

使用AngularFire查找/连接数据

  •  0
  • Buzz.K  · 技术社区  · 10 年前

    我有一个问题,在前端显示之前,如何组合来自不同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?

    谢谢

    1 回复  |  直到 10 年前
        1
  •  0
  •   Mathew Berg Lucas    10 年前

    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
    });