angularfirebase2 query where key equals value

时间:2019-01-18 18:10:25

标签: angular firebase firebase-realtime-database

I'm giving shot at firebase, converting an existing database to firebase. How do i select a list where the value of a key equals a specific value?

getAllUsers() {
    return this.fireBase.list(
        '/users',
        ref => ref
            .orderByChild('last_name')
            // active = true
    ).valueChanges();
}

1 个答案:

答案 0 :(得分:1)

With the Firebase Realtime Database you cannot use orderBy() on one field and then use equalTo() on another field. And you cannot use two different orderBy().

This is detailed/explained in the docs, here (angularfire2 ) and here ("standard" Javascript SDK).

However you could use a composed value like active_lastname with a query like the following one:

  var database = firebase.database();
  database
    .ref('users')
    .orderByChild('composedValue')
    .startAt('true_')
    .endAt('true_\uf8ff')
    .once('value', function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var childKey = childSnapshot.key;
        var childData = childSnapshot.val();
        console.log(childKey);
        console.log(childData);
      });
    });

You composed values would be like:

true_Obama
true_Bush
false_Carter
....

So for angularFire2, based on your code it would be:

getAllUsers() {
    return this.fireBase.list(
        '/users',
        ref => ref
            .orderByChild('composedValue')
            .startAt('true')
            .endAt('true\uf8ff')
    ).valueChanges();
}