Firebase数组提取未加载到页面加载

时间:2017-03-20 18:54:29

标签: angularjs firebase angular-promise

// Movements Controller
app.controller("MovementsCtrl", ["$scope", "$rootScope", "$filter", "$timeout", "$route", function($scope, $rootScope, $filter, $timeout, $route) {
  $rootScope.pageName = "Movements";

  var date = new Date();
  var currentDate = $filter('date')(new Date(), 'MM/dd/yyyy');

  $scope.labels = [];
  $scope.data = [];
  $scope.recordsArray = []; // Converts records object into an array.
  console.log($scope.recordsArray);

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      $rootScope.userID = user.uid;

      // Run query to pull user records.
      $timeout(function() {
        var userID = $rootScope.userID;
        var query = firebase.database().ref('/users/' + userID +'/movements/').orderByChild('created');

        query.on("value", function(snapshot) {
            $scope.records = snapshot.val();

              angular.forEach($scope.records, function(element) {
                $scope.recordsArray.push(element);
                $scope.labels.push(element.name);
                $scope.data.push(element.weight);
              });
        });
      });
    } else {
      console.log("not signed in");
    }
  });

  $scope.addRecord = function() {
    console.log("Pushed");
    var recordID = database.ref().push().key;
    var userID = $rootScope.userID;

    database.ref('users/' + userID + '/movements/' + recordID).set({
      user: userID,
      name: "Front Squat",
      sets: 5,
      reps: 5,
      weight: 350,
      created: currentDate
    });
    $route.reload();
  }
}]);

由于某些原因,我的页面在我的JS加载中的数组之前加载,呈现一个空页面。我试过在init()函数中包装所有内容并加载它,但仍然是同样的问题。任何人都可以帮我弄清楚如何预先加载我的JS数组或是否有其他解决方案?

感谢。

1 个答案:

答案 0 :(得分:1)

某些原因我的网页在数组之前加载

作为Firebase方法参数提供的函数由Firebase API保存,直到数据从服务器到达。这些函数以异步方式执行。这意味着它们在封闭函数完成后执行

在AngularJS框架及其摘要周期之外异步发生的范围更改不会触发对DOM的更改。将事件引入AngularJS框架的一种技术是将ES6承诺转换为$ q服务承诺:

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      $rootScope.userID = user.uid;

      // Run query to pull user records.
      //$timeout(function() {
        var userID = $rootScope.userID;
        var query = firebase.database().ref('/users/' + userID +'/movements/').orderByChild('created');

        //USE $q.when 
        $q.when(query.once("value")).then(function(value) {
            $scope.records = value;

              angular.forEach($scope.records, function(element) {
                $scope.recordsArray.push(element);
                $scope.labels.push(element.name);
                $scope.data.push(element.weight);
              });
        });
      //});
    } else {
      console.log("not signed in");
    }
  });

使用$ q与AngularJS框架及其摘要周期正确集成的服务承诺。

  

$ q.when

     

将可能是值的对象或(第三方)随后的承诺包含到$q承诺中。当您处理可能会或可能不是承诺的对象,或者承诺来自不可信任的来源时,这非常有用。

     

-- AngularJS $q Service API Reference - $q.when