Sunteți pe pagina 1din 14

LAB 3: FIREBASE REALTIME CRUD MOBILE APP

In this lab will show you how to access the Firebase Real-time Database. Not just accessing
but run CRUD (Create, Read, Update, Delete) operation for populating Firebase Real-time
Database.
What we build here just the Ionic 4, Angular 6 and Firebase CRUD app for Bulletin Board
which just create an information then show the list of information in the home page of the
app. There also details of information, edit and delete the bulletin board information.
The Following tools, frameworks, and modules are required for this lab:
 Node.js
 Ionic 4
 Angular 6
 Firebase NPM Module
 Firebase/Google Account
 Terminal or Node.js Command Line
 IDE or Text Editor
Before moving to the steps, make sure you have installed the latest Node.js and Ionic 4. To
check it, type this command in the terminal or Node.js command line.

node -v
v8.11.1
npm -v
6.2.0
ionic -v
Ionic CLI PRO 4.0.2
cordova -v
7.1.0

That's the last version when this lab was written. For update Node.js and it's `npm` download
from Node.js https://nodejs.org and choose the recommended version. For Ionic 4, type this
command.

sudo npm i -D -E ionic@latest


sudo npm i -g cordova

Lab Objectives
After completing this lab, you will be able to:
 Setup Firebase
 Create a New App
 Install and Configure Firebase Module
 Add List of Bulletin Board
 Add Page for Create Bulletin Board Info
 Add Page for Show Bulletin Board Info Detail
 Add Page for Edit Bulletin Board Info

Firebase Realtime CRUD Mobile App 3-1


 Launch Show Time!

Lab Procedures
A. Setting up Firebase
Go to console.firebase.google.com and log in using your google account.

Click CREATE NEW PROJECT button, name it as you like and choose your
country. Finally, click CREATE PROJECT button.

Firebase Realtime CRUD Mobile App 3-2


Go to Develop menu then choose Database then scroll to `Or choose Real-time
Database` then click `Create Database`.

Choose `Start in test mode` then click `Enabled` button.

Now, the Firebase Real-time Database is ready to use.

B. Creating a New App


To create a new Ionic 4 / Angular 6 app, type this command.

ionic start ionic-firebase-crud blank --type=angular

You will see questions during the installation, just type `N` for now. Next, go to the
newly created app folder.

cd ./ionic-firebase-crud

Firebase Realtime CRUD Mobile App 3-3


For sanitizing, run the app on the browser for the first time to make sure everything
working properly.

ionic serve -l

Type `Y` if asking to install `@ionic/lab`. Now, the browser will open automatically
then you will see this Ionic 4 Lab page.

C. Installing and Configuring Firebase Module


Firebase library ship with NPM module. For that, type this command to install the
module.

npm install --save firebase

Next, register the Firebase module in the Ionic 4 / Angular 6 app by open and edit this
file `src/app.component.ts` then add this import.

import * as firebase from 'firebase';

Declare a constant variable for holds Firebase setting before `@Component`.

const config = {
apiKey: 'YOUR_APIKEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DATABASE_URL',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
};

Add this line inside the `initializeApp` function for running the Firebase
configuration.

Firebase Realtime CRUD Mobile App 3-4


initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
firebase.initializeApp(config);
}

Now, Firebase database is ready to populate.

D. Adding List of Bulletin Board


We will use existing Ionic 4 / Angular 6 home page for display the list of the bulletin
board. Open and edit `src/app/home/home.page.ts` then add this import.

import { AlertController } from '@ionic/angular';


import { Router, ActivatedRoute } from '@angular/router';
import * as firebase from 'Firebase';

Declare variables before the constructor for hold bulletin board list and referencing
Firebase database.

infos = [];
ref = firebase.database().ref('infos/');

Add this Firebase function to listening any value changes from Firebase Database.

constructor(public router: Router, public alertController :


AlertController ) {
this.ref.on('value', resp => {
this.infos = [];
this.infos = snapshotToArray(resp);
});
}

Add this constant function below the Class block for converting Firebase response to
an array.

export const snapshotToArray = snapshot => {


let returnArr = [];

snapshot.forEach(childSnapshot => {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});

return returnArr;
};

Add a function under the constructor for navigating to `add-info` page.

Firebase Realtime CRUD Mobile App 3-5


addInfo() {
this.router.navigate(['/add-info']);
}

Add a function for edit info data.

edit(key) {
this.router.navigate(['/edit/'+key]);
}

Add an asynchronous function for delete info data.

async delete(key) {
const alert = await this.alertController.create({
header: 'Confirm!',
message: 'Are you sure want to delete this info?',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: (blah) => {
console.log('cancel');
}
}, {
text: 'Okay',
handler: () => {
firebase.database().ref('infos/'+key).remove();
}
}
]
});

await alert.present();
}

Finally, open and edit `src/app/home/home.page.html` then replace all tags with
this.

<ion-header>
<ion-toolbar>
<ion-title>
Info List
</ion-title>
<ion-buttons slot="end">
<ion-button routerLink="/create"><ion-icon name="add-
circle"></ion-icon></ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>

<ion-content>
<ion-list>

Firebase Realtime CRUD Mobile App 3-6


<ion-item-sliding *ngFor="let info of infos">
<ion-item detail lines="full" routerLink="/detail/
{{info.key}}">
<ion-icon name="desktop" slot="start"></ion-icon>
{{info.info_title}}
</ion-item>
<ion-item-options side="end">
<ion-item-option color="primary"
(click)="edit(info.key)">EDIT</ion-item-option>
<ion-item-option color="danger"
(click)="delete(info.key)">DELETE</ion-item-option>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>

E. Adding Page for Create Bulletin Board Info


To create a new Angular 6 page, we use Ionic 4 CLI to generate it. Type this command
for generating it.

ionic g page create

Next, open and edit `src/app/create/create.module.ts` then add or modify this


import to add `ReactiveFormsModule`.

import { FormsModule, ReactiveFormsModule } from


'@angular/forms';

Add this `ReactiveFormsModule` to `@NgModule` imports.

imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule,
RouterModule.forChild(routes)
],

Next, open and edit `src/app/create/create.page.ts` then add this imports.

import * as firebase from 'Firebase';


import { ActivatedRoute, Router } from '@angular/router';
import { FormControl, FormGroupDirective, FormBuilder,
FormGroup, NgForm, Validators, FormArray } from
'@angular/forms';

Inject that modules to the constructor params.

constructor(private route: ActivatedRoute,


public router: Router,

Firebase Realtime CRUD Mobile App 3-7


private formBuilder: FormBuilder) { }

Add this variables before the constructor.

ref = firebase.database().ref('infos/');
infoForm: FormGroup;

Initialize the info FormBuilder inside the constructor body.

constructor(private route: ActivatedRoute,


public router: Router,
private formBuilder: FormBuilder) {
this.infoForm = this.formBuilder.group({
'info_title' : [null, Validators.required],
'info_description' : [null, Validators.required]
});
}

Next, add the function to post the form data to the Firebase Real-time Database.

saveInfo() {
let newInfo = firebase.database().ref('infos/').push();
newInfo.set(this.infoForm.value);
this.router.navigate(['/detail/'+newInfo.key]);
}

Finally, open and edit `src/app/create/create.page.html` then replace all HTML


5 tags with this.

<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>Create Info</ion-title>
</ion-toolbar>
</ion-header>

<ion-content padding>
<form [formGroup]="infoForm">
<ion-item>
<ion-label position="floating">Info Title</ion-label>
<ion-input type="text"
formControlName="info_title"></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Info Description</ion-
label>
<ion-input type="text"
formControlName="info_description"></ion-input>
</ion-item>

Firebase Realtime CRUD Mobile App 3-8


<ion-button shape="round" color="primary" expand="block"
[disabled]="!infoForm.valid" (click)="saveInfo()">Save</ion-
button>
</form>
</ion-content>

F. Adding Page for Show Bulletin Board Info Detail


Create a new Ionic 4 / Angular 6 page by type this command for generate it.

ionic g page detail

Open and edit `src/app/detail/detail.page.ts` then add this imports.

import * as firebase from 'Firebase';


import { ActivatedRoute, Router } from '@angular/router';

Inject that module to the constructor.

constructor(private route: ActivatedRoute,


public router: Router) { }

Declare a variable before the constructor.

info = {};

Load info data from Firebase Real-time Database to the body of the constructor.

constructor(private route: ActivatedRoute,


public router: Router) {

firebase.database().ref('infos/'+this.route.snapshot.paramMap.g
et('key')).on('value', resp => {
this.info = snapshotToObject(resp);
});
}

Create this class for converting Firebase Real-time Database response to the Angular 6
object.

export const snapshotToObject = snapshot => {


let item = snapshot.val();
item.key = snapshot.key;

return item;
}

Finally, open and edit `src/app/detail/detail.page.html` then replace all HTML


tags with this.

<ion-header>

Firebase Realtime CRUD Mobile App 3-9


<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>Info Details</ion-title>
</ion-toolbar>
</ion-header>

<ion-content padding>
<ion-card>
<ion-card-content>
<ion-card-title>{{info.info_title}}</ion-card-title>

<p>{{info.info_description}}</p>
</ion-card-content>
</ion-card>
</ion-content>

G. Adding Page for Edit Bulletin Board Info


Create a new Ionic 4 / Angular 6 page by type this command for generating it.

ionic g page edit

Next, open and edit `src/app/edit.module.ts` then add or modify this import to
add `ReactiveFormsModule`.

import { FormsModule, ReactiveFormsModule } from


'@angular/forms';

Add this `ReactiveFormsModule` to `@NgModule` imports.

imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule,
RouterModule.forChild(routes)
],

Open and edit `src/app/edit/edit.page.ts` then add this imports.

import * as firebase from 'Firebase';


import { ActivatedRoute, Router } from '@angular/router';
import { FormControl, FormGroupDirective, FormBuilder,
FormGroup, NgForm, Validators, FormArray } from
'@angular/forms';

Inject that module to the constructor.

constructor(private route: ActivatedRoute,

Firebase Realtime CRUD Mobile App 3-10


public router: Router,
private formBuilder: FormBuilder) { }

Declare a variable before the constructor.

ref = firebase.database().ref('infos/');
infoForm: FormGroup;

Create a function for load info data based on the key that gets from params.

getInfo(key) {
firebase.database().ref('infos/'+key).on('value', resp => {
let info = snapshotToObject(resp);

this.infoForm.controls['info_title'].setValue(info.info_title);

this.infoForm.controls['info_description'].setValue(info.info_d
escription);
});
}

Call that function after initializing the FormGroup to the body of the constructor.

constructor(private route: ActivatedRoute,


public router: Router,
private formBuilder: FormBuilder) {
this.infoForm = this.formBuilder.group({
'info_title' : [null, Validators.required],
'info_description' : [null, Validators.required]
});
this.getInfo(this.route.snapshot.paramMap.get('key'));
}

Create this class for converting Firebase Real-time Database response to the Angular 6
object.

export const snapshotToObject = snapshot => {


let item = snapshot.val();
item.key = snapshot.key;

return item;
}

Add this function to update the data from the FormGroup to the Firebase Real-time
Database.

updateInfo() {
let newInfo =
firebase.database().ref('infos/'+this.route.snapshot.paramMap.g
et('key')).update(this.infoForm.value);

Firebase Realtime CRUD Mobile App 3-11


this.router.navigate(['/detail/'+this.route.snapshot.paramMap.g
et('key')]);
}

Finally, open and edit `src/app/edit/edit.page.html` then replace all HTML tags
with this.

<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>Edit Info</ion-title>
</ion-toolbar>
</ion-header>

<ion-content padding>
<form [formGroup]="infoForm">
<ion-item>
<ion-label position="floating">Info Title</ion-label>
<ion-input type="text"
formControlName="info_title"></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Info Description</ion-
label>
<ion-input type="text"
formControlName="info_description"></ion-input>
</ion-item>
<ion-button shape="round" color="primary" expand="block"
[disabled]="!infoForm.valid"
(click)="updateInfo()">Update</ion-button>
</form>
</ion-content>

H. Launch Show Time!


This is the time to show what we have built so far. The Ionic 4, Angular 6 and
Firebase CRUD mobile apps. Type this command to run this app in the browser.

ionic serve -l

And here we go, just test all of the CRUD function of this Ionic 4, Angular 6 and
Firebase app.

Firebase Realtime CRUD Mobile App 3-12


Firebase Realtime CRUD Mobile App 3-13
To run on the device, type this series of commands.

ionic cordova platform rm android


ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios
ionic cordova run android
ionic cordova run ios

That it's, the Ionic 4, Angular 6 and Firebase CRUD mobile apps. You can get the
working full source code in our lab files.

Firebase Realtime CRUD Mobile App 3-14

S-ar putea să vă placă și