Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Angularfire2 - listening on queried list child added

I'm wondering if it is possible to use "child_added" event with queried lists. Like so:

this.curUserPosts = this.af.database.list('/posts', {
    query: {
      orderByChild: 'user/id',
      equalTo: id
    }
  }).$ref.on("child_added", (child) => {
     console.log(child);
  });

I'm interested in the following here: Would it work at all. Would it properly fire only when added child corresponds to the query. How performant it is.

And also, what is the preferred way to handle such queried lists in firebase?

like image 800
Daniil Andreyevich Baunov Avatar asked Jan 18 '17 13:01

Daniil Andreyevich Baunov


1 Answers

No, it will not work; it will not have the query applied.

The ref$ property of the FirebaseListObservable will not be the ref with which the query was configured. You can see this in the source code (the constructor's ref parameter is assigned to the $ref property):

return new FirebaseListObservable(ref, subscriber => {
  ...
  let queried: firebase.database.Query = ref;
  if (query.orderByChild) {
    queried = queried.orderByChild(query.orderByChild);
  } else if (query.orderByKey) {
    queried = queried.orderByKey();
  } else if (query.orderByPriority) {
    queried = queried.orderByPriority();
  } else if (query.orderByValue) {
    queried = queried.orderByValue();
  }

However, if you want to use child_added yourself, you can compose your own query:

this.curUserPosts = this.af.database.list('/posts', {
  query: {
    orderByChild: 'user/id',
    equalTo: id
  }
});
this.curUserPosts.$ref
  .orderByChild('user/id')
  .equalTo(id)
  .on("child_added", (child) => {
     console.log(child);
  });

Note that, in your code, by calling on on the $ref, your this.curUserPosts property will be assigned something other than the observable; it will be assigned the listener you passed to on.

like image 117
cartant Avatar answered Nov 19 '22 22:11

cartant