Search code examples
javascriptfirebasegoogle-cloud-firestoreangularfire2

How to call method inside .subscribe?


I'm trying out Angular8 and Google Firestore. I'd like to add some additional information regarding a "member" when a member is a authenticated user. But, I only like to do this if the member-document doesn't exist. For this I'm using the attached code. The problem is that the addMember-method can't be called from where I would like it to be called (see attached code). This gives this error: "ERROR TypeError: this.addMember is not a function".

addMember can be called with out problem if it's placed "outside" of ".subscribe(function (doc) {".

Why is this? Any suggestions on solving this would be appriciated.


createMember() {
    alert(this.member.email);
    var docRef = this.db.collection("member").doc(this.member.orgId + '_' + this.member.email);


    docRef.get().subscribe(function (doc) {
      if (doc.exists) {
        console.log("Document data: ", doc.data());
      } else {
        this.addMember();
        //console.log('No such document! -> Add Member');
        // doc.data() will be undefined in this case

      }

    });

}

addMember(){
      this.userService.addMember(this.member)
        .then(res => {
          alert('Success!');
        });
  }

Solution

  • You can use a paramater, for example self

    let self = this;
    docRef.get().subscribe(function (doc) {
          if (doc.exists) {
            console.log("Document data: ", doc.data());
          } else {
            self.addMember();
            //console.log('No such document! -> Add Member');
            // doc.data() will be undefined in this case
    
          }
    
    });