webbuild infotech

Firebase

Add Extra Details on firebase users table

The Add Extra Details on the firebase users table So log in and registration functionality is easy to implement in firebase because there is already some login function provide by the firebase package. But let say if you want to manage the multiples fields for the user then how will you manage? like Firstname, Lastname, Address, etc…

The Add Extra Details on the firebase users table.

If you wondering to find the solution to implementing multiple fields in the users’ table with firebase then you are in the right place, and we will discuss all things about that in the current blog.

In the firebase createUserWithEmailAndPassword() this function is used to signup the form where access the email and password field and create a user in firebase.

First, need to import the module as given below.

import { AngularFireAuth } from "@angular/fire/auth";
Note: if this AngularFireAuth package is not available then please install with the npm.
Now let’s create the object in the constructor so with that object we can use the all function of AngularFireAuth in the whole class.
 constructor(private firebaseAuth: AngularFireAuth) {}

In the above code, you can see the private firebase auth so with firebase auth we can use the all function of AngularFireAuth in the current component.

Now let’s create the registration function in service.ts  so this service file will use in the angular component where get the information from the form submit and pass the value in the function.

  registration(data:any,password: any) {
    return this.firebaseAuth.auth.createUserWithEmailAndPassword(data.Email, password)
      .then(res => {
        data.UserId = res.user.uid;
        data.PhoneNumbers = [{
          NumberType: '',
          NumberValue: ''
        }];
        data.PhotoUrl = '';
        data.Addresses = [{
          AddressLine1: '',
          AddressLine2: '',
          City: '',
          State: '',
          Country: '',
          PostalCode: '',
          AddressType: ''
        }];
        data.IsDeleted = false;
        this.fireStore.doc(`users/${res.user.uid}`).set(data);
        this.toastr.success('User has been register successfully!', 'Successfull!');
        return true;
      }).catch(err => {
        switch (err.code) {
          case 'auth/email-already-in-use':
            this.toastr.error(`Email address ${data.Email} already in use.`, 'Error!');
            break;
          case 'auth/invalid-email':
            this.toastr.error(`Email address ${data.Email} is invalid.`, 'Error!');
            break;
          case 'auth/operation-not-allowed':
            this.toastr.error('Error during sign up.', 'Error!');
            break;
          case 'auth/weak-password':
            this.toastr.error('Password is not strong enough. Add additional characters including special characters and numbers.', 'Error!');            
          break;
          default:
            this.toastr.error(err.message, 'Error!');
            break;
        }
      });
  }
Note: So before implementing this code we need to add the users’ table in the firebase database and then make the changes in code.
In the firebase there is by default user table will find in Authentication where some fields are available like Name, Email, Password etc.. but still we can create the users’ table in firebase cloud and add the extra fields.
So now let’s create the component.ts for the Angular code where we use the above registration function
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../Services/auth.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MustMatch } from '../../../helpers/must-match.validator';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import 'firebase/firestore';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AngularFireAuth } from '@angular/fire/auth';
import { ToastrService } from 'ngx-toastr';

@Component({
   selector: 'app-registration',
   templateUrl: './registration.component.html',
   styleUrls: ['./registration.component.scss']
})
export class RegistrationComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
inputClicked = '';
closeResult = '';
firstname = '';
lastname = '';
DisplayName = '';

constructor(public authService: AuthService, private toastr: ToastrService,
private formBuilder: FormBuilder, private modalService: NgbModal, 
private fireStore: AngularFirestore, private firebaseAuth: AngularFireAuth,) { }

Userdata: any;
ngOnInit(): void {
   this.registerForm = this.formBuilder.group({
       firstname: ['ez-shopper', Validators.required],
       lastname: ['shopper', Validators.required],
       DisplayName: ['ez-shopper shopper', Validators.required],
       Email: ['ez-shopper@gmail.com', [Validators.required, Validators.email]],
       password: ['', [Validators.required, Validators.minLength(6)]],
       confirmPassword: ['', Validators.required]
   }, {
     validator: MustMatch('password', 'confirmPassword')
   });
}

// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }

//on registration form submit
async onSubmit() {
   this.submitted = true;
   // stop here if form is invalid
   if (this.registerForm.invalid) {
      return;
   }
   let response = await this.authService.registration(this.registerForm.value, this.registerForm.value.password);

   }
}

 

HTML code for UI

<form class="registration_form" [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<!-- firstname -->
<span class="form-group input-field ui-float-label">
   <input type="text" id="firstname" formControlName="firstname" [(ngModel)]="firstname" class="form-control"
   [ngClass]="{ 'is-invalid': submitted && f.firstname.errors }" pInputText (keypress)="patchDisplayName()">
   <label for="ffirstname">Firstname </label>
   <div *ngIf="submitted && f.firstname.errors" class="invalid-feedback">
      <div *ngIf="f.firstname.errors.required">firstname is required</div>
   </div>
</span>

<!-- lastname -->
<span class="form-group input-field ui-float-label">
   <input type="text" ng-model="input" id="lastname" [(ngModel)]="lastname" formControlName="lastname" class="form-control"
   [ngClass]="{ 'is-invalid': submitted && f.lastname.errors }" pInputText (keypress)="patchDisplayName()">
   <label for="lastname">Lastname</label>
   <div *ngIf="submitted && f.lastname.errors" class="invalid-feedback">
      <div *ngIf="f.lastname.errors.required">lastname is required</div>
   </div>
</span>

<!-- DisplayName -->
<span class="form-group input-field ui-float-label">
   <input type="text" id="DisplayName" formControlName="DisplayName" [(ngModel)]="DisplayName" class="form-control"
   [ngClass]="{ 'is-invalid': submitted && f.DisplayName.errors }" pInputText>
   <label for="DisplayName">Display Name</label>
   <div *ngIf="submitted && f.DisplayName.errors" class="invalid-feedback">
      <div *ngIf="f.DisplayName.errors.required">DisplayName is required</div>
   </div>
</span>

<!-- Email -->
<span class="form-group input-field ui-float-label">
  <input type="Email" id="Email" formControlName="Email" class="form-control"
   [ngClass]="{ 'is-invalid': submitted && f.Email.errors }" pInputText />
  <label for="Email">Email</label>
  <div *ngIf="submitted && f.Email.errors" class="invalid-feedback">
     <div *ngIf="f.Email.errors.required">Email is required</div>
  </div>
</span>

<!-- password -->
<span class="form-group input-field ui-float-label">
   <input type="password" id="password" (click)="inputClick($event)" formControlName="password" class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f.password.errors }" pInputText />
   <label for="fpassword">Password</label>
   <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
     <div *ngIf="f.password.errors.required">Password is required</div>
     <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
   </div>
</span>

<!-- confirmPassword -->
<span class="form-group input-field ui-float-label">
   <input type="Password" id="confirmPassword" (click)="inputClick($event)" formControlName="confirmPassword"
   class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" pInputText />
   <label for="confirmPassword">Confirm Password</label>
   <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
      <div *ngIf="f.confirmPassword.errors.required">ConfirmPassword is required</div>
      <div *ngIf="f.confirmPassword.errors.mustMatch">Passwords must match</div>
    </div>
</span>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>

In the above code, all the HTML and angular UI implemented with the Angular

Leave a Comment

Your email address will not be published. Required fields are marked *