In this Ionic 5 tutorial, we’ll integrate Google’s Firebase and use NoSQL database service Firestore to perform CRUD operation by creating a Student Resister application.
The Firestore is a cloud-based Realtime NoSQL database service provided by Firebase. We’ll integrate Firestore services in an Ionic application and build a Student Register application and perform CRUD (Create, Read, Update and Delete) operations.
In a traditional SQL based Relational Database Management system works with Tables and Rows, but in a NoSQL database like Firestore, we work with Collections and Documents. In a NoSQL, database information is saved and fetched in the form of JSON objects.
The Student Register application which we are going to create will have a form using which we’ll add a new document for each student having Name, Age and Address in the collection of Students. We’ll also add update, list and delete operation on Student collection.
Let’s begin…
Also See: How to Implement Firestore CRUD Operation in Angular 7/6 Application
# Update Ionic CLI
Run following npm command to update the Ionic CLI tool to the latest version
$ npm install -g @ionic/cli</pre> <h3># Create new Ionic application:</h3> Execute the following command to create a new Ionic Angular application with a <code>blank
template:$ ionic start ionic-firebase-crud-operations blank --type=angular </pre> then move to the root path of the application <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-firebase-crud-operations</pre> <h4></h4> <h3># Create a Firebase Project</h3> If you already having any Firebase project, you can use that or follow these steps to create one and enable Firestore database. After creating a Firebase project we will use credentials in our Ionic Application. <strong>Step 1)</strong> Visit <strong>Firebase</strong> <a href="https://firebase.google.com/" target="_blank" rel="noopener noreferrer">here</a> then click on Get Started if you have not created an account yet. <a href="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_6-1.png"><img class="alignnone wp-image-1857" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_6-1.png" alt="" width="287" height="209" /></a> <strong>Step 2)</strong> Click on "<strong>Add project</strong>" then enter app-related information click on "<strong>Create project</strong>" <a href="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_7-1.png"><img class="alignnone size-full wp-image-1858" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_7-1.png" alt="" width="523" height="504" /></a> <strong>Step 3)</strong> Next click on "<strong>Web App</strong>" icon to get configuration text with app secret info which we will add in our Ionic Application to communicate with services related to this Firebase project. <a href="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_8-1.png"><img class="alignnone wp-image-1859" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_8-1.png" alt="" width="336" height="236" /></a><a href="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_9-1.png"><img class="alignnone wp-image-1860" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/Screenshot_9-1.png" alt="" width="402" height="277" /></a> <strong>Step 4) </strong>Then enable Firestore Database service in your Firebase project. On the left sidebar select Database, then click on the <strong>Create</strong> button. This will enable the Database service for our Firebase application. Now we are ready to connect our Ionic application with this Firebase application. <h3></h3> <h3># Adding Firebase Credentials in Ionic 5 Application</h3> Now we need to add the Firebase application credential in the Ionic application to create a connection. Open the Environment file at location "~ionic-firebase-crud-operations/src/environments<strong>/environment.ts</strong>" then update it with your credential as shown below: <pre class="wp-block-prismatic-blocks"><code class="language-javascript">export const environment = { production: false, firebase: { apiKey: "[YOUR_apiKey_HERE]", authDomain: "[YOUR_authDomain_HERE]", databaseURL: "[YOUR_databaseURL_HERE]", projectId: "[YOUR_projectId_HERE]", storageBucket: "[YOUR_storageBucket_HERE]", messagingSenderId: "[YOUR_messagingSenderId_HERE]", appId: "[YOUR_appId_HERE]" } };</pre> <h3></h3> <h3># Install Firebase in Application</h3> To integrate Firebase services, we'll install <code>angularfire
package in the Ionic Angular application. It is a Firebase official package for Angular applications. This package lets an Angular project to use all Firebase services. As a dependency, we also need to install thefirebase
package which will work under the hood withangularfire
. Install these packages by running following npm command in the terminal window$ npm install firebase @angular/fire --save</pre> <h3># Import Firebase Modules</h3> We need to import the required <code>AngularFireModule
and also theAngularFirestoreModule
to use the Firestore NoSQL database service. To create a connection between Firebase application with Ionic Angular application, we will use theAngularFireModule
'sinitializeApp
method to takeenvironment.firebase
credentials. After making above changes the app.module.ts file will look like this// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { environment } from 'src/environments/environment'; import { AngularFireModule } from '@angular/fire'; import { AngularFirestoreModule } from '@angular/fire/firestore'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [ BrowserModule, IonicModule.forRoot(), AppRoutingModule, AngularFireModule.initializeApp(environment.firebase), AngularFirestoreModule ], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule { }by following above steps your application is connected with Firebase and ready to perform CRUD operation on Firestore Database.
# Create a Service with Firestore CRUD methods
Now we'll create a new service to perform CRUD operation by using methods available in the AngularFirestore class.
Run the following
ionic generate
command to createfirebaseService
in the services folder in the Ionic application.$ ionic generate service services/firebase</pre> <h3># Update the FirebaseService with CRUD methods</h3> After creating the service at location "~ionic-firebase-crud-operations/src/app/service/<strong>firebase.service.ts</strong>", update it with CRUD methods <div>Replace below code in the <strong>firebase.service.ts</strong> file</div> <div> <pre class="wp-block-prismatic-blocks"><code class="language-javascript">// firebase.service.ts import { Injectable } from '@angular/core'; import { AngularFirestore } from '@angular/fire/firestore'; @Injectable({ providedIn: 'root' }) export class FirebaseService { collectionName = 'Students'; constructor( private firestore: AngularFirestore ) { } create_student(record) { return this.firestore.collection(this.collectionName).add(record); } read_students() { return this.firestore.collection(this.collectionName).snapshotChanges(); } update_student(recordID, record) { this.firestore.doc(this.collectionName + '/' + recordID).update(record); } delete_student(record_id) { this.firestore.doc(this.collectionName + '/' + record_id).delete(); } } </pre> <div>In the above service, import the <code>AngularFirestore
class to use its methods. Following are the methods doing operations onStudents
collection and manipulating the documents.
one an only working tutorial
but these codes are missing some codes.
//in app.module.ts
import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { RouteReuseStrategy } from ‘@angular/router’;
import { IonicModule, IonicRouteStrategy } from ‘@ionic/angular’;
import { AppComponent } from ‘./app.component’;
import { AppRoutingModule } from ‘./app-routing.module’;
import { initializeApp, provideFirebaseApp } from ‘@angular/fire/app’;
import { environment } from ‘../environments/environment’;
import { provideAuth, getAuth } from ‘@angular/fire/auth’;
import { provideDatabase, getDatabase } from ‘@angular/fire/database’;
import { AngularFireModule } from “@angular/fire/compat”;
import { AngularFireAuthModule } from “@angular/fire/compat/auth”;
import { AngularFireStorageModule } from ‘@angular/fire/compat/storage’;
import { AngularFirestoreModule } from ‘@angular/fire/compat/firestore’;
import { AngularFireDatabaseModule } from ‘@angular/fire/compat/database’;
import ‘firebase/storage’;
import { FormsModule } from ‘@angular/forms’;
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), FormsModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireAuthModule,
AngularFireStorageModule,
AngularFireDatabaseModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
bootstrap: [AppComponent],
})
export class AppModule {}