Firebase 同步处理

Firebase Sync handling

我的数据结构如下:

-Company
       |
      -jskdhjJKHh-Yty
        -companyName:CompanyTH

-Employees
   |
  -shdjasjdshy665-333
      |
     -empName:Peter
      |
     -Company
       -jskdhjJKHh-Yty:true

我在 ParentController 中推送 Employees 的数据,如下所示:

第 1 步:

var ref=firebase.database().ref("Employees");
var newKey=ref.push({empName:"John"}).key

设置 2:

var childCompany=ref.child(newKey+'/Company');
childCompany.set(true);

第 3 步:

$scope.emplist=$firebaseArray(ref);

HTML中:

<div ng-repeat="emp in emplist" ng-Controller="ChildController">
    <p>{{emp.empName}}</p>
    <p>{{CompanyName}}</p>
</div>

ChildController中:

var companyRef=firebase.database().ref("Company/"+Object.keys($scope.emp.Company)[0]);
$scope.CompanyName=$firebaseObject(companyRef);

问题是:

Step 1 执行它同步数据到 $scope.emplistChildController 为那个 ng-repeat 实例执行并且当 ChildController 中的代码尝试执行行 Object.keys($scope.emp.Company)[0] 它给出了 Company 未定义的错误。这个错误是因为 Step 2 没有被执行并且 firebaseStep 1 之后同步数据。但是当 Step 2 被执行时它更新 firebase-databaseChildController 会不在更新 ng-repeat 实例时执行。

我脑海中的一个解决方案是我可以停止 Firebase 同步数据直到所有推送查询完成吗?或者你们有任何其他解决方案吗?

注意一点:

当我在同一个应用程序会话中第二次 运行 时,上面提到的步骤成功执行,奇怪的是它在第一次尝试时没有 运行。

如果我没有正确理解您的问题,那么您可能需要稍微更改一下推送逻辑。

通过单个推送命令将数据保存在 Firebase 的特定节点中总是很方便。据我所知,您正试图分两步推送数据 Employees 节点。真的有必要吗?您可以一次轻松地同时推送 empNamechildCompany

并且在您的 ChildController 中,您需要向您尝试使用 ref.on 获取数据的节点添加一个侦听器。这样您就可以在 Firebase 数据库中成功存储数据后获得回调。

var companyRef=firebase.database().ref("Company/"+Object.keys($scope.emp.Company)[0]);
companyRef.on("value", function(data) {
  // This will be triggered once there's a
  // change in data in the node the reference is referring to
  doSomething();
});

更新

then how I can use set(true) within push?

取一个同时包含 empNamechildCompany 的对象。然后像这样使用推送。

// Get the firebase reference of your node
var ref = firebase.database().ref("Employees");

// Create an object first. 
var employee = {
  empName: "Peter",
  company: "CompanyTH"
};

// Pass the object that you've prepared earlier here. 
ref.push.set(employee);

这只是一个例子。你可以有嵌套对象。这个想法是一次传递整个对象并在 Firebase 中成功保存时添加回调。你可能也会想到这样的事情。

ref.set(employee, function(error) {
  if (error) {
    doSomethingOnError();
  } else {
    doSomethingOnDataSavedSuccessfully();
  }
});

您可以像这样尝试构建嵌套 类

var employee = {
  empName: "Peter",
  Company: {
    companyName: "Name",
    uniqueID: true
  }
};