skip to Main Content

Im trying to submit the user data to the firebase firestore database, but the function to create a new collection is not working for me, I have checked some diferent ways to do it, but none of theme are working, I already update my firebase config file using the firebase comands on my terminal.

This is the code to call the service that use firestore:

    this.authSvc.register(email, password).then((result) => {
      this.authSvc.logout();
      this.verifyEmail();
      this.res = result?.user;
      this.registerDB();
    
    })
    .catch((error) => {
        this.toastr.error(this.firebaseError.codeError(error.code), 'Error');
        this.loading = false;
    });

     
  }

  verifyEmail() {
    this.afAuth.currentUser.then(user => user?.sendEmailVerification())
    .then(() => {
      this.toastr.info('Se envio un correo con el link de verificación', 'Verificar Email')
      this.router.navigate(['/verify-email'])
    });
  }

  async registerDB() {
    const path = 'Users';
    const id = this.res.uid;
    this.userData.uid = id;
    this.userData.password = null;
    await this.frservice.createDoc(this.userData, path, id);
  }

And this is the code of the firestore service:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/compat/firestore';

@Injectable({
  providedIn: 'root'
})
export class FirestoreService {

  constructor(private firestore: AngularFirestore) { }

  createDoc(userData: any, path: string, id: string) {

    const collection = this.firestore.collection(path);
    return collection.doc(id).set(userData);

  }

  getId() {
    return this.firestore.createId();
  }

  getCollection<tipo>(path: string) {

    const collection = this.firestore.collection<tipo>(path);
    return collection.valueChanges();
  }

  getDoc<tipo>(path: string, id: string) {
    return this.firestore.collection(path).doc<tipo>(id).valueChanges()
  }


}

I just want to create a new collection were the user’s data are going to be registered.

2

Answers


  1. Chosen as BEST ANSWER

    I resolved the problem, It was the rules of the firestore DB:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if false;
        }
      }
    }
    

    I change it for this rule:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    

    The issue was that I didn't had the permission to write.


  2. You should put an await before the this.registerDB(); call. Don’t forget make you arrow function async!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search