Adam
Adam

Reputation: 2517

AngularFirebase 2 check if user exists then add to database

I want to add a new user to firebase realtime Database, i have managed to query the databse to find if the email input already exists

onSubmit(form: NgForm){

    var user = this._visitorService.getIndividualVisitor(form.value.email);

    user.valueChanges().subscribe(list=>{
      console.log(list);
      if(list.length ===0 ){
        console.log('email doesnt exist, creating new user');
        this._visitorService.addVisitor(form.value)  
      } else{
        console.log('email existst');
        this._visitorService.updateVisitor(form.value)
      }
    })
}
  
getIndividualVisitor(email:string){
    this.list = this.firebase.list('visitors', ref => ref.orderByChild('email').equalTo(email));
    return this.list;
}

The problem i have is that the user.valueChanges() is called every time the database is updated this means that every time I add a new user the update user function is also called, what would be the correct way to do this. I am using "angularfire2": "^5.0.0-rc.4", and "firebase": "4.8.0",

Upvotes: 0

Views: 456

Answers (1)

Kim
Kim

Reputation: 1198

I think using Firebase Auth together with Cloud Functions would solve your issue.

Use Firebase Authentication to create a user.

Then deploy a Cloud Function which listens on the user OnCreate event.

exports.newUser = functions.auth.user().onCreate(event => {
  // Add something to your database here.
});

Documentation for Cloud Function Triggers can be found here: Firebase Authentication Triggers

Upvotes: 1

Related Questions