Select Firebase 和 Angular Fire 中 key=value 的所有内容

Select everything where key=value in Firebase and Angular Fire

我有一个 firebase 数据库,如下所示:

我将 courseID 变量存储在我的 $state.params.courseID 参数中,现在我只想在 coursedID$state.params.courseID 匹配的地方提取 Sections变量,然后将结果存储在一个数组中,这是我目前尝试的方法:

    var sectionsRef = firebase.child('Sections');
    sectionsRef
    .orderByChild('courseID')
    .on('value', function(snap) {
      console.log(snap.val(), 'Sections');
      console.log(snap.key(), 'Key');
    });
    $scope.sections = $firebaseArray(sectionsRef);

我真的很困惑如何在 Firebase 中进行这样的基本查询。

您可以将equalTo()方法与orderByChild()结合使用。

var sectionsRef = firebase.child('Sections');
sectionsRef
.orderByChild('courseID')
.equalTo('And now?');
$scope.sections = $firebaseArray(sectionsRef);

如果你想在你的路由上更流畅,你可以创建一个工厂,通过 courseID 检索课程并在路由器中解析它。

angular.module('app', ['firebase'])
  .config(ApplicationConfig)
  .constant('FBURL', 'https://<my-fb-app>.firebaseio.com/')
  .service('RootRef', ['FBURL', Firebase)
  .factory('Sections', Sections)
  .controller('SectionsCtrl', SectionsCtrl);

function Sections(RootRef, $firebaseArray) {
  var sectionRef = RootRef.child('sections');
  return {
    byCourseId: function byCourseId(value) {
      sectionsRef
        .orderByChild('courseID')
        .equalTo(value);
      return $firebaseArray(sectionsRef);
    }
  }
}

function ApplicationConfig($stateProvider) {
  $stateProvider
    .state("sections", {
      controller: "SectionsCtrl",
      templateUrl: "views/sections.html",
      resolve: {
        sections: function(Sections, $state) {
          return Sections.byCourseId($state.params.courseid);
        }
      }
    });
}

function SectionsCtrl($scope, sections) {
   // This is the resolved data in your controller
   $scope.sections = sections;
}