6

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

3

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.

cartant
  • 57,105
  • 17
  • 163
  • 197
-1

Yes, this should work for all initial items of list.

Once child_added is called for all initial items, then for every future item that's added child_added will be called, but it won't be sorted anymore.

JoKr
  • 4,976
  • 8
  • 27
  • 39