Angular Firebase Cheat Sheet!

Published by Abhay Rastogi on

Firebase is a widely used mobile and website development kit by google firebase team. firebase comes with a variety of development tools which makes Application development fast than ever before.

Angular Firebase Cheat Sheet covers all essential things which are needed for creating a variety of web applications such as Authentication, posting data and retrieving data from cloudfirestore and uploading an image on firebase.

Authentication

Authorizing folks to use the website is not an easy task a single flaw can lead to a personal data breach and making a custom authentication server is time-consuming and costly. firebase provides a variety of authentication services which saves much time and cost.

Create a new firebase project then register web app and copy Firebase SDK snippet in environment.ts

Enable email and password sign method in the Authentication section of firebase

export const environment = {
  production: false,
  firebase: {
    apiKey: " ",
    authDomain: " ",
    databaseURL: " ",
    projectId: " ",
    storageBucket: " ",
    messagingSenderId: " ",
    appId: " "
  }
};

Install angularfire

npm install firebase @angular/fire --save

Import angular firebase dependence and initialize environment settings in app.module.ts

import { environment } from '../environments/environment';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireAuthModule } from '@angular/fire/auth';

@NgModule({
    imports: [
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFirestoreModule,
    ]
})

Generate new angular service then create a firebase login method

ng generate service firebaseService 
import { AngularFireAuth } from  "@angular/fire/auth";
export class firebaseService{

constructor(private afAuth: AngularFireAuth) { }

//Create new user 
createUser(email: string, password: string) {
  
    return new Promise((resolove, reject) => {
      this.afAuth.auth
      .createUserWithEmailAndPassword(email, password)
      .then(userData => resolove(userData), err => reject(err)
        );
    });
  
}


//Login user
login(email: string, password: string) {
  
    return new Promise((resolove, reject) => {
      this.afAuth.auth
        .signInWithEmailAndPassword(email, password)
        .then(userData => resolove(userData), err => reject(err)
        );
    });
  }

}

Import firebaseService.ts in component

import { FirebaseServiceService } from '../firebaseService.service';

export class YourComponent implements OnInit {
  constructor(public authService: FirebaseServiceService){}

 createNewUser() {
    this.authService
   .createUser('yourEmail@codesearchonline.com','yourPassword')
    .then(res => {
       console.log("Valid User");
    })
    .catch(err => console.log(err.message));   
}

checkUser() {
    this.authService
    .login('yourEmail@codesearchonline.com','yourPassword')
    .then(res => {
       console.log("Valid User");
    })
    .catch(err => console.log(err.message));   
}


}

Create user email and password with firebase rest request for more info visit(https://firebase.google.com/docs/reference/rest/auth).

Copy project Web API Key from project settings

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

export class YourComponent implements OnInit {

 postRequest() {
    let records = {};
    records['email'] = 'yourEmail@codesearchonline.com';
    records['password'] = 'yourPassword';
    const  headers = new  HttpHeaders().set("Content-Type", "application/json");
      this.http.post('https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key= API_KEY',records,{headers})
      .subscribe(user=>console.log(user.localId)
    );   
  }

}

Routing Guard

Creating a routing guard let authorized users can only access a certain page of Web App!

ng generate guard firebaseAuthGuard

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from '@angular/fire/auth';
import { first } from 'rxjs/operators';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class FirebaseAuthGuard implements CanActivate {
users:any;
  constructor(public useruth: AngularFireAuth,private router: Router) { 

  }

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

   if(this.useruth.authState.pipe(first()).toPromise())
   {
     return true;
   } 
   else{
     this.router.navigate(['/login']);
   }
  }
}

Update app-routing.ts

import { FirebaseAuthGuard } from './firebaseAuthGuard.guard';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';

const routes: Routes = [
  {path: 'login',component: LoginComponent}, 
  {path: 'dashboard',component: DashboardComponent,canActivate:[FirebaseAuthGuard]}, 
];

const config: ExtraOptions = {
  useHash: true,
};

@NgModule({
  imports: [RouterModule.forRoot(routes, config)],
  exports: [RouterModule],
})
export class AppRoutingModule {
}

CloudFirestore

Similarly, firebase also provides CloudFirestore to store data in NoSQL formate. a complex query can also be fired in CloudFirestore such as AND OR EQUAL TO very easily. data can be added modified or deleted in CloudFirestore at realtime

CloudFirestore CRUD Operations

  • Insert data in a firebase collection
import { AngularFirestore } from '@angular/fire/firestore';
export class firebaseService{

constructor(private firestore: AngularFirestore) { }

//Insert data in collection
 insert_userdetail(detail) {
    return this.firestore.collection('user').add(detail);
  }

//Read data from collection
 read_userdetail() {
     return this.firestore.collection('user').snapshotChanges();
  }


}
import { FirebaseServiceService } from '../firebaseService.service';
import { AngularFireAuth } from '@angular/fire/auth';
@Component({
  selector: 'front-page',
   template: `
    <div>
      <ul>
         <li *ngFor="let user of showuser"  >
            <p>{ user.firstName } </p>
           <p>{ user.lastName  } </p>
         </li>
      </ul>
    </div>
  `
  styleUrls: ['./front-page.component.scss']
})
export class YourComponent implements OnInit {
  
  showuser:any;
  constructor(public cloudFirestore: FirebaseServiceService){
      read();
}
 
insert(){   
    let record = {};
    record['firstName'] = 'codesearch';
    record['lastName'] = 'online';
   
 //Insert data
 this.cloudFirestore.insert_userdetail(record)
     .then(resp => { console.log("Data added!"); })
     .catch(error => { console.log(error); });

}

//Read data 
read(){
      this.cloudFirestore.read_userdetail().subscribe(data=>
         {
            this.showuser = data.map(e=>{
              return{
                 firstName:e.payload.doc.data()['firstName'],
                 lastName:e.payload.doc.data()['lastName'],
                     };
              })
          });
     }

}

Add and read data from a specific document of collection

insert_userdetail(detail,docId) {
    return this.firestore.collection('user').doc(docId).set(detail);
}

read_userdetail(docId) {
     return this.firestore.collection('user').doc(docId).snapshotChanges();
  }

Cloudfirestore Query


read_userdetail() {
return this.firestore.collection('user',ref =>  ref.where('type','==','editor')
.where('isPublish','==','true'))
.snapshotChanges();
  }
  • Update Data
update_userdetail(detail,docId) {
     return this.firestore.collection('user').doc(docId).update(detail);
  }
  • Delete Data
delete_userdetail(docId) {
     return this.firestore.collection('user').doc(docId).delete();
  }

Upload File

Firebase also gives storage option for saving files or images. after uploading file in firebase project it automatically creates URL of that upload file.

Upload file in firebase

import { AngularFireStorageReference, AngularFireUploadTask, AngularFireStorage } from '@angular/fire/storage';
import { Observable } from 'rxjs/Observable';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'front-page',
   template: `<input type="file" formControlName="attach" (change)="uploads($event)" placeholder="attach files/links">`
  styleUrls: ['./front-page.component.scss']
})
export class YourComponent implements OnInit {

 constructor(private firestore:AngularFirestore,private afStorage: AngularFireStorage){ }


uploads(event){
        this.attachment=event.target.files[0];
        const randomId = Math.random().toString(36).substring(2);
        const file = this.attachment;
        const filePath = 'userAttachment/';
        this.ref = this.afStorage.ref(filePath +randomId);
        this.task = this.ref.put(file);
        this.task.snapshotChanges().pipe(
           finalize(() => {
             this.ref.getDownloadURL().subscribe((url)=>{
                 
                  //Save Upload URL in Cloudfirestore
                  this.firestore.collection('user').add(
                 {  
                  attach:url,
                  type:"JPEG",
               
                 });
          
           })
         ).subscribe();
     }

}

Current User Detail

In some scenarios, the Angular application also requires current login detail for slowing profile image, user name or UID of the user which might be required throughout the application.

Get current user detail

import { AngularFirestore } from '@angular/fire/firestore';
import { first } from 'rxjs/operators';

export class CheckLoginComponent implements OnInit {
 constructor( public useruth: AngularFireAuth){
     this.getUserdetail();
  }
 
  isLoggedIn() {
    return this.useruth.authState.pipe(first()).toPromise();
 }
 
 async getUserdetail() {
    const user = await this.isLoggedIn()
     if (user) {
       console.log(user.uid);
       console.log(user.email);
       console.log(user.image);
       console.log(user.phone);
    
      }else{
        console.log("user doesn't exist !");
     }
   }

}


7 Comments

Mithlesh · 8th December 2019 at 9:49 am

nice blog!

Brian · 9th December 2019 at 4:48 pm

Are you sure that the following code will validate if the user is authenticated? Would this not return a promise, which would evaluate to a truthy?

this.useruth.authState.pipe(first()).toPromise()

Vladimirsnr · 30th December 2020 at 10:14 pm

Thank You!

Sergcwf · 15th January 2021 at 3:15 pm

Saved my life…..

Svetlanaqew · 17th January 2021 at 12:07 pm

Thanks a lot!

Ivanqbp · 19th January 2021 at 7:57 am

nice article

Leave a Reply

Avatar placeholder

Your email address will not be published.