0% found this document useful (0 votes)
68 views20 pages

11 Ionic App With Firebase

This document describes how to build an appointment booking app using Ionic and Firebase realtime database. It provides instructions on setting up a Firebase project, adding Firebase to an Ionic project, and performing CRUD operations to book, view, edit and delete appointments from the Firebase database in realtime. Key steps include initializing the Firebase SDK, defining an Appointment data model, creating an Appointment service to interface with the database, and updating component files to handle form submission and display appointment data from the database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views20 pages

11 Ionic App With Firebase

This document describes how to build an appointment booking app using Ionic and Firebase realtime database. It provides instructions on setting up a Firebase project, adding Firebase to an Ionic project, and performing CRUD operations to book, view, edit and delete appointments from the Firebase database in realtime. Key steps include initializing the Firebase SDK, defining an Appointment data model, creating an Appointment service to interface with the database, and updating component files to handle form submission and display appointment data from the database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Appointment Booking App with Real time Firebase

Database

Source : https://www.positronx.io/set-up-firebase-database-in-ionic-angular/
https://www.positronx.io/build-ionic-firebase-crud-app-with-angular/
SETTING UP FIREBASE WEB APP TO IONIC PROJECT

1. Go to Firebase website : https://console.firebase.google.com/

2. Create a project
3. Once the project has been successfully created, add firebase to your project. Choose
web App.
4. Copy the yellow codes as it will be added to your ionic project later.
5. Click at Realtime Database. Then Create Database.
CREATING AN IONIC PROJECT AND ADDING FIREBASE WEB APP TO IONIC
PROJECT

1. Create the app


ionic start ionic-firebase-setup blank –type=angular

2. Go to your project folder (cd ionic-firebase-setup)and install firebase


package in the app project

npm install firebase @angular/fire –save

3. Add firebase config key – you need to get the key from your Firebase Project App in
the environment.ts file.
PLEASE ENSURE THAT YOU COPY THE ENVIRONMENT CONFIG FROM YOUR
FIREBASE.

environment.ts

//get your own key and paste the key here

export const environment = {


  production: false,
  firebaseConfig : {
    apiKey: "AIzaSyCyQbFXXXXXXXXXXXXXXxdqqifu410JBVqjFwZI",
    authDomain: "ionicfirebase-11111.firebaseapp.com",
    projectId: "ionicfirebase-111111",
    storageBucket: "ionicfirebase-90149.appspot.com",
    messagingSenderId: "974170831374",
    appId: "1:974170831374:web:986fb9b40061fe03699a5f"
  }
};
4. import and register firebase in AppModule
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 firebase + environment


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 { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFirestoreModule,
    AngularFireStorageModule,
    AngularFireDatabaseModule,

  ],
  providers: [{ provide: RouteReuseStrategy, useClass:
IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}
5. Create two more pages
ionic generate page make-appointment
ionic generate page edit-appointment

make-appointment page will be use to add a new appointment while edit-


appointment page will be used to edit the existing appointment.

6. Edit app.component.html to add tabs on the front page.


app.component.html

<ion-app>
  <ion-router-outlet></ion-router-outlet>
</ion-app>
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button routerLinkActive="tab-selected" routerLink="/home"
class="ios" tab="home">
      <ion-icon name="list-box"></ion-icon>
      <ion-label>Appointments</ion-label>
    </ion-tab-button>
    <ion-tab-button routerLinkActive="tab-selected" routerLink="/make-
appointment" class="ios" tab="make-appointment">
      <ion-icon name="add-circle"></ion-icon>
      <ion-label>Book Appointment</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

7. Create a shared folder in your project. Then, create a new file called
Appointment.ts in that folder.
Appointment.ts

export class Appointment {


  $key: string;
  name: string;
  email: string;
  mobile: number;
}

8. Create a service called as appointment in the shared folder

ionic g service shared/appointment

9. Edit appointment.service.ts

appointment.service.ts

import { Injectable } from '@angular/core';


import { Appointment } from '../shared/Appointment';
import {
  AngularFireDatabase,
  AngularFireList,
  AngularFireObject,
} from '@angular/fire/compat/database';
@Injectable({
  providedIn: 'root',
})
export class AppointmentService {
  bookingListRef: AngularFireList<any>;
  bookingRef: AngularFireObject<any>;
  constructor(private db: AngularFireDatabase) {}
 
// Create or add a new appointment
  createBooking(apt: Appointment) {
    return this.bookingListRef.push({
      name: apt.name,
      email: apt.email,
      mobile: apt.mobile,
    });
  }
  // Get a single appointment record
  getBooking(id: string) {
    this.bookingRef = this.db.object('/appointment/' + id);
    return this.bookingRef;
  }
  // Get List
  getBookingList() {
    this.bookingListRef = this.db.list('/appointment');
    return this.bookingListRef;
  }
  // Update
  updateBooking(id, apt: Appointment) {
    return this.bookingRef.update({
      name: apt.name,
      email: apt.email,
      mobile: apt.mobile,
    });
  }
  // Delete
  deleteBooking(id: string) {
    this.bookingRef = this.db.object('/appointment/' + id);
    this.bookingRef.remove();
  }
}

To Perform CRUD (Create, Read, Update, Delete) operations, we need to edit the
following files.

1. Create/add Data
 make-appointment.module.ts
 make-appointment.page.ts
 make-appointment.page.html

2. Read the data


 home.page.ts
 home.page.html

3. Update the Data


 app-routing.module.ts
 edit-appointment.module.ts
 edit-appointment.page.ts
 edit-appointment.page.html

4. Delete/remove the Data


Just create a delete function in home.page.ts file.
C RUD
Create or add a new element into the list

1. Update make-appointment.module.ts to add ReactiveFormsModule.

make-appointment.module.ts

import { NgModule } from '@angular/core';


import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MakeAppointmentPageRoutingModule } from './make-appointment-
routing.module';
import { MakeAppointmentPage } from './make-appointment.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    ReactiveFormsModule,
    MakeAppointmentPageRoutingModule
  ],
  declarations: [MakeAppointmentPage]
})
export class MakeAppointmentPageModule {}
2. Update make-appointment.page.ts to add functions. Once the form is
submitted, createBooking() will be called to add a new object data into the database.

make-appointment.page.ts

import { Component, OnInit } from '@angular/core';


import { Router } from '@angular/router';
import { FormGroup, FormBuilder } from '@angular/forms';
import { AppointmentService } from './../shared/appointment.service';

@Component({
  selector: 'app-make-appointment',
  templateUrl: './make-appointment.page.html',
  styleUrls: ['./make-appointment.page.scss'],
})
export class MakeAppointmentPage implements OnInit {
  bookingForm: FormGroup;

  constructor(
    private aptService: AppointmentService,
    private router: Router,
    public fb: FormBuilder
  ) { }

  ngOnInit() {
    this.bookingForm = this.fb.group({
      name: [''],
      email: [''],
      mobile: ['']
    });
  }

  formSubmit() {
    if (!this.bookingForm.valid) {
      return false;
    } else {
      this.aptService.createBooking(this.bookingForm.value).then(res =>
{
        console.log(res);
        this.bookingForm.reset();
        this.router.navigate(['/home']);
      })
        .catch(error => console.log(error));
    }
  }
}
3. Update make-appointment.page.html

make-appointment.page.html

<ion-header>
  <ion-toolbar class="ios hydrated" color="secondary">
    <ion-title class="ios title-ios hydrated">Booking</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-list lines="full">
    <form [formGroup]="bookingForm" (ngSubmit)="formSubmit()">
      <ion-item>
        <ion-label position="floating">Name</ion-label>
        <ion-input formControlName="name" type="text" required></ion-
input>
      </ion-item>
      <ion-item>
        <ion-label position="floating">Email</ion-label>
        <ion-input formControlName="email" type="text" required>
        </ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="floating">Mobile</ion-label>
        <ion-input formControlName="mobile" type="text" required>
        </ion-input>
      </ion-item>
      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full"
expand="block">Book Appointment</ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>
</ion-content>
C RD U
Read the list from the database and Remove a data from
the list.

1. To display the list of appointment and to delete the booking, edit home.page.ts
home.page.ts

import { Component, OnInit } from '@angular/core';


import { Appointment } from '../shared/Appointment';
import { AppointmentService } from './../shared/appointment.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  Bookings = [];
  constructor(
    private aptService: AppointmentService
  ) { }
  ngOnInit() {
    this.fetchBookings();
    let bookingRes = this.aptService.getBookingList();
    bookingRes.snapshotChanges().subscribe(res => {
      this.Bookings = [];
      res.forEach(item => {
        let a = item.payload.toJSON();
        a['$key'] = item.key;
        this.Bookings.push(a as Appointment);
      });
    });
  }
  fetchBookings() {
    this.aptService.getBookingList().valueChanges().subscribe(res => {
      console.log(res);
    });
  }
  deleteBooking(id) {
    console.log(id);
    if (window.confirm('Do you really want to delete?')) {
      this.aptService.deleteBooking(id);
    }
  }
}
2. Edit home.page.html to display the list
home.page.html

<ion-header>
  <ion-toolbar color="secondary">
    <ion-title>
      Dr. Mashi's Consultation
    </ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-list class="ios list-ios hydrated">
    <ion-list-header class="ios hydrated">
      Appointments
    </ion-list-header>
    <ion-item *ngFor="let booking of Bookings" class="user-list">
      <ion-label>
        <h5>
          <ion-icon name="person"></ion-icon> {{booking.name}}
        </h5>
        <p>
          <ion-icon name="call"></ion-icon> {{booking.mobile}}
        </p>
      </ion-label>
      <div class="item-note" item-end>
        <button ion-button clear [routerLink]="['/edit-appointment/',
booking.$key]">
          <ion-icon name="create" style="zoom:2.0"></ion-icon>
        </button>
        <button ion-button clear (click)="deleteBooking(booking.$key)">
          <ion-icon name="trash" style="zoom:2.0"></ion-icon>
        </button>
      </div>
    </ion-item>
  </ion-list>
CR U D
Update the existing data

1. To update the data, you need to update the app-routing.module.ts first.

app-routing.module.ts
2. Edit edit-appointment-module.ts to include the reactiveform.

edit-appointment.module.ts

import { NgModule } from '@angular/core';


import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';

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

import { EditAppointmentPageRoutingModule } from './edit-appointment-


routing.module';

import { EditAppointmentPage } from './edit-appointment.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    ReactiveFormsModule,
    EditAppointmentPageRoutingModule
  ],
  declarations: [EditAppointmentPage]
})
export class EditAppointmentPageModule {}

3. Edit edit-appointment.page.ts to include related update function

edit-appointment.page.ts

import { Component, OnInit } from '@angular/core';


import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder } from '@angular/forms';
import { AppointmentService } from './../shared/appointment.service';
@Component({
  selector: 'app-edit-appointment',
  templateUrl: './edit-appointment.page.html',
  styleUrls: ['./edit-appointment.page.scss'],
})
export class EditAppointmentPage implements OnInit {
  updateBookingForm: FormGroup;
  id: any;
  constructor(
    private aptService: AppointmentService,
    private actRoute: ActivatedRoute,
    private router: Router,
    public fb: FormBuilder
  ) {
    this.id = this.actRoute.snapshot.paramMap.get('id');
    this.aptService.getBooking(this.id).valueChanges().subscribe(res =>
{
      this.updateBookingForm.setValue(res);
    });
  }
  ngOnInit() {
    this.updateBookingForm = this.fb.group({
      name: [''],
      email: [''],
      mobile: ['']
    });
    console.log(this.updateBookingForm.value);
  }
  updateForm() {
    this.aptService.updateBooking(this.id,
this.updateBookingForm.value)
      .then(() => {
        this.router.navigate(['/home']);
      })
      .catch(error => console.log(error));
  }
}

4. Edit edit-appointment.page.html for the screen design

edit-appointment.page.html

<ion-header>
  <ion-toolbar color="secondary">
    <ion-title>
      Edit Appointment
    </ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-list lines="full">
    <form [formGroup]="updateBookingForm" (ngSubmit)="updateForm()">
      <ion-item>
        <ion-label position="floating">Name</ion-label>
        <ion-input formControlName="name" type="text" required></ion-
input>
      </ion-item>
      <ion-item>
        <ion-label position="floating">Email</ion-label>
        <ion-input formControlName="email" type="text" required>
        </ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="floating">Mobile</ion-label>
        <ion-input formControlName="mobile" type="text" required>
        </ion-input>
      </ion-item>
      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full"
expand="block">Update Appointment</ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>
</ion-content>

That’s all

You might also like