1

我试图将Firebase快照的结果作为数组返回,以便我可以通过它们ng-repeat(默认情况下,它返回对象)最后一行是我尝试设置的位置数组中的对象并将它们设置为重复范围。但我似乎对将值设置为数组的基本概念感到困惑:/任何帮助都很棒。将Firebase快照作为数组获取并设置为范围

const businessKey = '-KQ1hFH0qrvKSrymmn9d'; 
const rootRef = firebase.database().ref(); 
const discoverRef = rootRef.child('discover'); 
const businessRef = rootRef.child('businesses'); 


function getDiscoverBarContent(key, cb) { 
    discoverRef.child(key).on('child_added', snap => { 
     let businesRef = businessRef.child(snap.key); 
     businesRef.once('value', cb); 
    }); 
} 

getDiscoverBarContent(businessKey, snap => { 
    snap.forEach((child) => { 
     var item = {}; 
     item._key = snap.val(); 
     array.push(item); 
     /*$scope.discover = array*/ 
     }) 
}); 

回答

0

我相信其他的答案可以工作,但我真的不想摧毁我为了使用另一种方法而拥有的东西。下面是我用来解决这个问题的代码:

$scope.discover = []; 
const businessKey = $scope.finalItem.$id; 
const rootRef = firebase.database().ref(); 
const discoverRef = rootRef.child('discover'); 
const businessRef = rootRef.child('businesses'); 


function getDiscoverBarContent(key, cb) { 
    discoverRef.child(key).on('child_added', snap => { 
     let businesRef = businessRef.child(snap.key); 
     businesRef.once('value', cb); 
    }); 
} 

getDiscoverBarContent(businessKey, snap => { 
    var snapVal = snap.val(); 
    $scope.discover.push(snapVal); 
}); 

首先,为了防止错误的缘故,我们增加了顶部$scope.discover = []。 其次,我无法通过Firebase对象forEach。相反,我需要将snap.val()设置为一个变量,并将其推送到我的$scope.discover。如预期的那样,现在可以通过ng-repeat="place in discover track by $index"重复数据。感谢您的其他建议,但是这对我当前的代码更好。如果重新开始,我一定会记住其他建议。

0

尝试angularfire

Angularfire是一个方便的firebase帮手,为您提供一些有用的工具来构建角应用程序。它包括3项主要服务。只需在每个控制器中注入您需要的那个。确保火力点已经第一次初始化:

$firebaseAuth $firebaseObject $firebaseArray

这里是你如何使用$firebaseArray

const businessKey = '-KQ1hFH0qrvKSrymmn9d'; 
const rootRef = firebase.database().ref(); 
const discoverRef = rootRef.child('discover'); 
const businessRef = rootRef.child('businesses'); 


function getDiscoverBarContent(key, cb) { 
    let myArray = $firebaseArray(discoverRef.child(key)); 
    myArray.$loaded().then(() => { cb(a) }); 
} 

getDiscoverBarContent(businessKey, data => { 
    // ctrl.property = data 
    // $scope.property = data; 
}); 

如果我有任何语法错误,我很抱歉。我仍然使用经典的JS语法,不管这个es5/es6是什么,它都叫它。

的文档angularfire:https://github.com/firebase/angularfire/blob/master/docs/reference.md

无关,但如果你需要在角轻松分页,可以救自己的麻烦和使用下列库:https://github.com/deltaepsilon/firebase-paginator