Crud Operation Using Firebase Cloud Firestore with ionic Angular

firebase image

A lot of people asked: why is firebase used? why firebase is better than SQL and how does firebase store data?

In this article, you will learn how to implement Firebase cloud Firestore with Ionic Angular and perform CRUD operations (CREATE, READ, UPDATE AND DELETE).

Firebase is a backend as a service platform that allows you to build web and mobile with no server-side programming.

The first thing to do is to visit firebase and create a project and hit the continue button.

Select your account and hit the submit button

After the loading process, your project will be ready. Hit the continue button, thereafter you should see

get started with firebase

Click on the Settings icon on the left and a pane you pop

firebase create project

Click on your icon below to create a firestore database.

firebase creates a firestore database.

Next, you can set the rules for your newly created firestore database.

firestore database rules

Firestore rules involve who can read or write to your database. To learn more about firestore rules, use this link.

The next thing to do is get your application configuration settings. This can be found in the project settings section.

firestore project settings

Click on the red spot I did above, The next page requires a nickname for your application. Enter a nickname and register App.

After successful registration, you should see your application configuration, just like below. That is the only part you need for now.

var firebaseConfig = {
    apiKey: "AIzaSyD074oun2fe79VnDmzONcmp7pHAkZVl-tc",
    authDomain: "my-sample-project-ddf0b.firebaseapp.com",
    projectId: "my-sample-project-ddf0b",
    storageBucket: "my-sample-project-ddf0b.appspot.com",
    messagingSenderId: "587824708708",
    appId: "1:587824708708:web:355de7751acf39b835f371",
    measurementId: "G-4HQKMC6PTT"
  };

Thie above configuration should be declared in your environment.ts file.

Next, you should install firebase and angular fire to your project with the following command.

npm install @angular/fire firebase

Next, you should initialize firebase in your app.module.ts file. Add the following line to your import array.

 AngularFireModule.initializeApp(environment.firebaseConfig),

Next, create an interface and a service file.

//userInterface.ts

export interface User {
  id: string;
  name: string;
  age: number;
  gender: string;

}

Above the interface for storing data to the firebase.

//firebaseService.ts
import { User } from 'src/app/interfaces/userInterface';
import { Injectable } from '@angular/core';
import { AngularFireStorage} from '@angular/fire/storage';
import { AngularFirestore } from '@angular/fire/firestore';

  constructor(
    public afs: AngularFirestore
    ) { }

The above is the firebaseService.ts file. It will interact with the firebase database. This is where the CRUD operation will take place.

This method below will create a new record in the firestore database.

Create Record

saveUser(userDetails: User) {
      return this.afs.collection('user-collection').doc(userDetails.id).set(userDetails);
    }

Read Record

getUser(user:User){
var docRef = afs.collection("user-collection").doc(user.id);

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});
}

Update Record

   updateUser(user: User){
      const itemRef = this.afs.collection('user-collection').doc(user.id);
      const setWithMerge = itemRef.update({
          name : user.name,
      age: user.age,
      gender: user.gender
    });

    }

Delete Record

  deleteUser(id){
     return this.afs.collection('user-collection').doc(id).delete();
    }

Find Record Where

 findUserById(id) {
      const result = this.afs.collection('user-collection', ref => ref.where('id', '==', id)).valueChanges();
      return result;
    }

// Using this query will listen to changes. user Subscription instance to unsubscribed after getting your data. example below

import { Subscription } from 'rxjs';

export class ReportComponent implements OnInit {
userSub : Subscription;

  constructor(
      private fireService: FirebaseService
    ) {}
     
  this.fireService.findUserById().subscribe(user => {
        
        console.log(user);
      this.userSub.unsubscribed();
      });
  

}

For more queries, visit the Firebase documentation.

swagasoft

Fully stack(MEAN) software engineer with over five years of experience participating in the complete product development lifecycle of successfully launched applications. Eager and willing to deliver mission- critical technology solutions.

View all posts by swagasoft →

Leave a Reply

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