在Firebase中使用Ionic异步数据检索的问题

Trouble in Asynchronous data retrieving in Firebase using Ionic

本文关键字:数据 检索 问题 异步 Ionic Firebase      更新时间:2023-09-26

我对Ionic和Firebase绝对陌生,并试图创建一个示例项目,我试图使用值检查从Firebase数据库查询。为了说清楚,因为Firebase不允许在SELECT查询条件中使用WHERE子句,所以我试图学习如何处理这个问题。

这是我的Firebase数据库的快照。

我的目的只是在我的视图中显示数组中地址值为700030的数据,就像我们在AngularJS中使用ng-repeat一样。

var app = angular.module('starter', ['ionic', 'firebase'])
app.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
app.controller('MainCtrl', function($scope, $firebaseArray){
       
	var ref = new Firebase('https://helpee-70271.firebaseio.com');
	
	$scope.result = $firebaseArray(ref);
	
	ref.orderByChild("address").on("child_added", function(data) {
	   console.log("Initially :" + JSON.stringify($scope.result));
       	   //console.log(data.val().address);
	   if(data.val().address == "700030"){
	      console.log(data.val().address);
	      $scope.result.push(data.val());
	   }
	   console.log(JSON.stringify($scope.result));
	});
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <!--Firebase addition start -->
    <script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
    <!--Firebase addition end -->
    
    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter">
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title text-center">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content ng-controller="MainCtrl">
         <div>
	    <div ng-repeat ="results in result">
	         <div>{{results.name}}</div>
		     <div>{{results.phNumber}}</div>
	    </div>
	 </div>
      </ion-content>
    </ion-pane>
  </body>
</html>

这是我的代码片段。我得到的问题是,虽然数据的检查和检索正在正确地完成,但在视图中我看到包含所有元素的数组,无论地址检查如何,首先打印的是应该打印的值。

这是视图和浏览器控制台的快照

有没有人可以帮助我如何纠正这个问题,并解释我哪里出错了?我会非常感激,因为我真的很新的这一点,我愿意学习。提前感谢!!

你的问题是你填充你的数组两次。首先使用以下行处理所有数据:

$scope.result = $firebaseArray(ref);

然后添加你想要的数据到child_added监听器中

$scope.result.push(data.val());
因此,简单的解决方案是将第一行更改为:
$scope.result = [];