Search code examples
firebaseangular6angularfire2

AngularFire 2 "child_added" returning all childs


I'm having difficulties in understanding the "child_added" from angularfire2.

According to the documentation, the "child_added", should return all children the first time, and then listen only for new children added to that particular db node.

With my code, the first time I get all children as expected. The problem is when I add a new child to the userinfo node, I still get all the children (including the newly added).

Does this mean that the "child_added" is actually downloading all the children every time a new child is added?

My db structure

enter image description here

.ts code (relevant part)

 ngOnInit(){
   this.userService.getUsers().snapshotChanges(['child_added'])
     .subscribe(users => {        
       users.forEach(user=> {
         console.log(user.key)
       })
     })
 }

The service (relevant part)

 constructor(private firebaseApp: AngularFireDatabase) {}

 getUsers(){
   return this.firebaseApp.list('userinfo/')
 }

Thank you in advance


Solution

  • Since you're returning a new list every time getUsers is called, the child_added event will fire on each user in that list.

    If you want to only fire all users the first time and after that get changes, you should probably create the list only once and return it from there on:

    var usersList;
    
    constructor(private firebaseApp: AngularFireDatabase) {}
    
    getUsers(){
      if (!this.usersList) {
        this.usersList = this.firebaseApp.list('userinfo/')
      }
      return this.usersList;
    }