Ionic 应用程序数据中的 Firebase 3、AngularFire 2 未实时更新/实时更新(带视频演示)

Firebase 3, AngularFire 2 in Ionic app data not updating real time / live update (with Video demo)

Firebase 以其实时数据更新而闻名,所以这对我来说很奇怪。

我正在使用 Firebase 3(新​​的 firebase 控制台应用程序。想稍后添加身份验证)和 AngularFire 2。我使用 Ionic 的选项卡模板启动应用程序,因此 app.js' 路由器配置应该相同。

Click here to see a (90 second) video demo of the issue

我使用 'ionic serve --lab' 将我的离子应用程序提供给浏览器,因此我可以看到 iOS 和 Android 视图。

很少有其他观察结果:

HTML(包含切换):

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <button class="button button-block button-positive" ng-click="addProperty()">Add Test Property</button>
    <div class="list" ng-repeat="(key, property) in properties">
      <ion-toggle class="item item-divider" ng-model="property.status" ng-true-value="'on'"
        ng-false-value="'off'" ng-change="togglePower(property, key)"> {{ property.name }}
      </ion-toggle>
    </div>
  </ion-content>
</ion-view>

Index.html

<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>

<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>

<!-- Firebase & AngularFire --> // I tried saving them and loading from locally
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>

<script>
  // Initialize Firebase
  var config = {
    apiKey: "API_KEY",
    authDomain: "projectName.firebaseapp.com",
    databaseURL: "https://projectNamefirebaseio.com",
    storageBucket: "projectName.appspot.com"
  };
  firebase.initializeApp(config);
</script>

<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>

Controller.js

controller('DashCtrl', function ($scope) {
    var propertiesRef = firebase.database().ref('properties');

    propertiesRef.on('value', function (data) {
      $scope.properties = data.val();
    }, function (errorObject) {
      console.log("Error getting the properties: " + errorObject.code);
    });

    var id = 0;
    $scope.addProperty = function () {
      propertiesRef.push({
        name: "Test " + id++,
        status: "on"
      }).then(function () {
        console.log("Property Added!");
      });
    };

    $scope.togglePower = function (device, key) {
      propertiesRef.child(key).update({
        "status": device.status
      });
    };
};

如果需要任何其他信息,请告诉我。我无法理解问题所在。

如您所见,当您在 android 应用程序中单击切换按钮时,所有切换按钮都会更新。这是因为当您执行点击时会触发 digest cicle

您应该在更新您的作用域变量后调用 $scope.$apply(),或者将其包装在超时中

controller('DashCtrl', function ($scope, $timeout) {
    var propertiesRef = firebase.database().ref('properties');

    propertiesRef.on('value', function (data) {
      $timeout(function() {
        $scope.properties = data.val();
      })
    }, function (errorObject) {
      console.log("Error getting the properties: " + errorObject.code);
    });
};