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.
I’m getting this error. pls help!
ERROR Error: Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.
Hi, tanks again for this valuable tutorial.
Please could you explain how the service:
~Ionic4Firestore/src/app/service/crud.service.ts
KNOWs that the DB under use is the DB specified in “environment .ts”.
Thanks
Hi!
Remember first that we have initialize the the database configuration in our app.mofule.ts like AngularFireModule.initializeApp(environment.firebase)
And the path called environment has been imported on the top page
Second thing is that in our crud.service.ts we have imported the import { AngularFirestore } from ‘@angular/fire/firestore’ which know how interpret the database configuration and from it our service use the interpretation of those configurations.
I tried to explain but I don’t know if it answer to your question.
Thank you guys! You saved me.
Its work. thank you!
GREAT!!! I tried a lot of tutorials for ionic4/CRUD but they don’t work.
Your tutorial works at my first trial.
Thanks a lot
Glad it helped! thanks for feedback really appreciate 🙂
I implemented the code from the tutorial above, but when “$ ionic serve” the app ignores the URL don’t showing it in the path and not accessing the required CRUD page. Even if i go in the browser and type the path to accessing it, after execute update browser to call the required CRUD page, the app ignores it and shows “http://localhost:8100/”. Always hangs on that!
Any help!
How can i filter by username, it’s possible with firebase?
It´s like this:
return this.firestore.collection(‘Student’, ref => ref.where(“FieldName”,”==”, name)).snapshotChanges();