Angular Firebase Cheat Sheet! Published by 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

environment.ts export const environment = { production: false, firebase: { apiKey: " ", authDomain: " ", databaseURL: " ", projectId: " ", storageBucket: " ", messagingSenderId: " ", appId: " " } }; 1 2 3 4 5 6 7 8 9 10 11 12 export const environment = { production : false , firebase : { apiKey : " " , authDomain : " " , databaseURL : " " , projectId : " " , storageBucket : " " , messagingSenderId : " " , appId : " " } } ;

Install angularfire

npm install firebase @angular/fire --save 1 npm install firebase @ angular / fire -- save

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

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, ] }) 1 2 3 4 5 6 7 8 9 10 11 12 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 1 ng generate service firebaseService

firebaseService.ts 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) ); }); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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

yourComponent.ts 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)); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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

yourComponent.ts 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) ); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 1 ng generate guard firebaseAuthGuard

firebaseAuthGuard.ts 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']); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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 & lt ; boolean | UrlTree > | Promise & lt ; 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 { } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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

firebaseService.ts 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(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 ( ) ; } }

yourComponent.ts 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'], }; }) }); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 import { FirebaseServiceService } from '../firebaseService.service' ; import { AngularFireAuth } from '@angular/fire/auth' ; @ Component ( { selector : 'front-page' , template : ` & lt ; div > & lt ; ul > & lt ; li * ngFor = "let user of showuser" > & lt ; p > { user . firstName } & lt ; / p > & lt ; p > { user . lastName } & lt ; / p > & lt ; / li > & lt ; / ul > & lt ; / 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(); } 1 2 3 4 5 6 7 8 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(); } 1 2 3 4 5 6 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); } 1 2 3 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(); } 1 2 3 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

uploadComponent.ts 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(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import { AngularFireStorageReference , AngularFireUploadTask , AngularFireStorage } from '@angular/fire/storage' ; import { Observable } from 'rxjs/Observable' ; import { AngularFirestore } from '@angular/fire/firestore' ; @ Component ( { selector : 'front-page' , template : ` & lt ; 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, 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