将Firebase快照作为数组获取并设置为范围

时间:2017-02-15 18:27:15

标签: javascript angularjs firebase firebase-realtime-database angularjs-ng-repeat

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

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*/
      })
});

2 个答案:

答案 0 :(得分:0)

尝试angularfire

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

$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

答案 1 :(得分: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 = []。 其次,我无法forEach通过Firebase对象。相反,我需要将snap.val()设置为变量并将其推送到我的$scope.discover。现在可以按预期通过ng-repeat="place in discover track by $index"重复数据。感谢其他建议,但这对我当前的代码更有效。如果重新开始,我肯定会记住其他建议。