Cloud Fire Store CRUD Operation Using Angular

What is cloud Firestore?

Cloud Firestore is a NoSql Document database built for automatic scaling,high performance,Real time,and ease of application development.Unlike a sql database, there are no table or rows. Instead, you store data in documents,which organized into collection.

(Source & Image Credit Google Cloud Platform)

All documents must be stored in collections. Documents can contain subcollections and nested objects, both of which can include primitive fields like strings or complex objects like lists.

Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.

Document:

In Cloud Firestore, the unit of storage is the document. A document is a lightweight record that contains fields, which map to values.

Collections:

Documents live in collections, which are simply containers for documents.

Screenshot (105).png

Here users_data is collection and document name will be obtained by auto key value.
So now it is time for action, we will see how to create firestore document and how to insert/fetch data from firestore database.

Prerequisites:

npm install firebase angularfire2 –save

Cloud Firestore Setup

After logged in to firebase console account  follow the steps.

  • Create Project
  • Navigate to Database tabScreenshot (106).png
  • Select Cloud Firestore Database and create project in test modeScreenshot (107).png
  • Now Add Collection by clicking Add CollectionScreenshot (108)Screenshot (109)Screenshot (110)

Setting Up Angular Application

  • First get configuration to connect firestore from angular by clicking setting buttonScreenshot (111).png
  • Now store the all configuration information into environment.ts fileScreenshot (112)
  • Environment.ts
export const environment = {

production: false,

firebase: {

apiKey: 'your key',

authDomain: 'your auth domain',

databaseURL: 'db url',

projectId: 'project id',

storageBucket: '',

messagingSenderId: 'sender id'

}};
  • Now first initialize our application with fire store configuration in our app.module.ts file as shown below
import { environment } from '../environments/environment';

import { AngularFireModule } from 'angularfire2';

import { AngularFirestoreModule } from 'angularfire2/firestore';

imports: [

BrowserModule,

AngularFireModule.initializeApp(environment.firebase),

AngularFirestoreModule
],

First import AngularFireModule and AngularFirestoreModule from angularfire2 and then initialize you application in imports array with the configuration which we had stored in environment.ts .

  • Now let us create the service to fetch the data from fire store database. And also create user class to provide some data structure. We can generate service using

ng g s firestore-data

user.ts


export class User {

public constructor(public id: string,public firstname: string,public lastname: string,public mobile_no: string) {

 }

}

firestore-data.service.ts

import the following packages to fetch the data from the server and store it in our observable.


import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';

import { User } from './user';

now create a collection which is type of our user class .

users: Observable<User[]>;

then create the instance of AngularFirestore  in constructor. And write the following code to fetch the data from user collection.


this.users = this._afs.collection('Users').valueChanges();

Collection without id

withoutid.png

from above method valueChanges() we can fetch data but not that auto-id. Which we will required to delete and update the record. So to fetch that auto-id field with data we should use snapshotChanges() as shown below

this.users = this._afs.collection('Users').snapshotChanges().map(

changes => {

return changes.map(

a => {

const data = a.payload.doc.data() as User;

data.id = a.payload.doc.id;

return data;

});
});

Collection with id

withid.png

  • Now it is time to display our data on our app.component file, to do so first let me inject our firestore-data.service in app.component.ts file as shown below
    import { FirestoreDataService } from './firestore-data.service';
    
    import { User } from './user';
    
    arr: User[] = [];
    
    constructor(public _data: FirestoreDataService) {
    
     }
    
  •  And now call our getUsers method inside  ngOnInit  method of component’s life cycle event hook as shown below. 
    ngOnInit() {
    
     this._data.getUsers().subscribe(
    
     (user: User[]) =>{
    
     this.arr = user;
    
    });
    
     }
    
  •  And on app.component.html let’s loop through the arr and display all the users on our page.
  • <div class="container"  *ngIf="arr.length>0;else noData">
    <ul *ngFor="let item of arr" class="list-group">
    	<li class="list-group-item">
    
    <strong>{{item.firstname}}{{item.lastname}}</strong> : {{item.mobile_no}}</li>
    &nbsp;</ul>
    &nbsp;
    
    </div>
    <div class="container">
    
    <ng-template #noData>
    
    <hr>
    
    <h5>There are no users to display</h5>
    </ng-template></div>
    </code>
    
    <img class="alignnone size-full wp-image-2213" src="https://jinalshahblog.files.wordpress.com/2017/12/output.png" alt="output.png" width="571" height="192" />
    <ul>
    	<li>
    <h1><strong>Add New User</strong></h1>
    <h1></h1>
    For Adding new user to collection we will need to adjust 3 things
    <ol>
    	<li>app.component.html</li>
    	<li>app.component.ts</li>
    	<li>firestore-data.service.ts</li>
    </ol>
    <h2><strong>html</strong></h2>
    </li>
    </ul>
    </li>
    </ul>
    
    <div class="container">
    <h1>Add New User</h1>
    <form (ngSubmit)="userSubmit()" #addform="ngForm">
    <div class="form-group">
    
    <label for="firstname">FirstName</label>
    
    <input type="text" [(ngModel)]="model.firstname" name="firstname" class="form-control" id="firstname" required #firstname="ngModel">
    
    </div>
    <div [hidden]="firstname.valid || firstname.pristine" class="alert alert-danger">
    
    Firstname is required
    
    </div>
    <div class="form-group">
    
    <label for="lastname">LastName</label>
    
    <input type="text" [(ngModel)]="model.lastname" name="lastname" class="form-control" id="lastname" required #lastname="ngModel">
    
    </div>
    <div [hidden]="lastname.valid || lastname.pristine" class="alert alert-danger">
    
    Lastname is required
    
    </div>
    <div class="form-group">
    
    <label for="mobile_no">Mobile Number</label>
    
    <input type="text" [(ngModel)]="model.mobile_no" name="mobile_no" class="form-control" id="mobile_no" required #mobileno="ngModel">
    
    </div>
    <div [hidden]="mobileno.valid || mobileno.pristine" class="alert alert-danger">
    
    Mobile number is required
    
    </div>
    <button type="submit" class="btn btn-default form-control" [disabled]="!addform.form.valid">Add User</button>
    
    </form>
    
    </div>
    
    • Ts

      
      model = { firstname: '', lastname: '', mobile_no: '' };
      
      userSubmit() {
      
      this._data.addUser(this.model);
      
       this.model.firstname = '';
      
      this.model.lastname = '';
      
       this.model.mobile_no = '';
      
       }
      
      

      Service

      In our Service file first we need to create usersCollection which is instance of AngularFirestoreCollection.

      userscollection: AngularFirestoreCollection<User>;
      

      And initialize this userscollection inside the constructor as shown below

      this.userscollection = this._afs.collection('Users', x => x.orderBy('firstname', 'asc'));
      

      here I had also used orderBy operator to sort data by first name in ascending order.

      Then finally the addUser method

      
      addUser(user) {
      
       this.userscollection.add(user);
      
       }
      
      

      Delete User

      Again in order to delete the particular user from the list we will required to change the 3 files.

      1. app.component.html
      2. app.component.ts
      3. firestore-data.service.ts

      html

      Add delete button app.component.html as shown below,

    
    <a (click)="onDelete(item)" >
    
    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
    
    </a>
    
    
    • Ts

      Create onDelete() method in app.component.ts as shown below,

      
      onDelete(user) {
      
      this._data.deleteUser(user);
      
       }
      
      

      Service

      first will create instance of AngularfirestoreDocument as shown below,

      userDoc: AngularFirestoreDocument<User>;
      

      then create deleteUser method inside the firestore-data.service file,

      deleteUser(user) {
      
      this.userDoc = this._afs.doc(`Users/${user.id}`);
      
      this.userDoc.delete();
       }
      
      

      final firestore-data.service.ts


    • final app.component.html

      final app.component.ts

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s