Lopes
Lopes

Reputation: 363

Firebase get document length inside collection

I am trying to get how many documents my collection has in order to setup next ID when adding a document.

I am using angularfire to connect to firebase. I have a service to get value from firebase

asignaturas.service.ts

addAsignatura() {
      return this.db.collection('asignaturas').valueChanges();
   }

asignaturas.component.ts

 onSend(){
    this.dbService.addAsignatura()
    .subscribe(data => {
      return this.size = data.length;
      
      
    });
    this.size = this.size + 1;
      this.docID = this.size.toString();
    this.dbService.getCollectionAsignaturas().doc(this.docID)
      .set({codigo: 12, nombre: 'xcssdf'});
   
  }

I have a button in html to send this information to firebase, so am trying to subscribe to the observable and count the length, my issue is that when i click for the first time in the button, nothing happens and the count var is not update, all works ok when i click for the second time

Upvotes: 1

Views: 450

Answers (1)

Naveen Chahar
Naveen Chahar

Reputation: 571

Since you are making an aynchronous call inside 'addAsignatura', the value of 'this.size' won't be updated until we get the result from that call. The program execution moves ahead in the meantime and executes the other statements.

In order to achieve the desired behaviour, place the remaining code inside the callback function like this :

    onSend(){
       this.dbService.addAsignatura()
        .subscribe(data => {
            this.size = data.length;
            this.size = this.size + 1;
            this.docID = this.size.toString();
            this.dbService.getCollectionAsignaturas().doc(this.docID)
             .set({codigo: 12, nombre: 'xcssdf'});
  
       }); 
    }

Upvotes: 1

Related Questions