How to set up Firebase Realtime Database in Ionic 4 and Angular 8 App?

How to set up Firebase Realtime Database in Ionic 4 and Angular 8 App?

In this Ionic 4 Firebase tutorial, you'll learn step by step how to set up Firebase Realtime Database in Ionic 4 and Angular 8 App. Firebase is a popularly known Google product and Its a NoSQL Realtime Database.

In this Ionic 4 Firebase tutorial, we are going to look at step by step how to set up Firebase Realtime Database in Ionic 4/Angular 8 project.

Firebase is a popularly known Google product and Its a NoSQL Realtime Database. Working with Firebase is easy, It doesn’t make its user to lost in its dashboard due to its superb User Experience. Firebase offers top-notch features for building web and mobile applications swiftly:

  • Cloud storage
  • Realtime update
  • Easy A/B Testing
  • Analytics Monitoring
  • Authentication support
  • Easy Server management
  • Single-page app hosting
  • Real-time communication
  • Hosting and cloud storage
  • Push notifications support
  • Google Cloud IoT tools Integration support

Firebase offers two services:

Cloud Firestore: It’s a modern Real-time NoSQL database with auto-scaling and more robust queries.

Real-time Database: It allows us to build an app which needs to be updated at real-time. e.g., stock market app, sports app, live chat app etc.

In this tutorial we will focus on Firebase Real-time Database.

Table of Contents

  1. Create Firebase Account
  2. Create Ionic 4/Angular Project
  3. Install Firebase Package in Ionic 4/Angular App
  4. Configure Firebase Config Keys in Ionic 4
  5. Import and Register Firebase in AppModule
  6. Conclusion
1. Create Firebase Account

Visit console.firebase.google.com and sign in using your Gmail account.

Click on the “create a project” button then click on continue button.

Next, click on the web icon as shown in the screenshot.

Next, add Firebase to your web app. Enter the app’s nickname and then click on the next button.

It will take you to the screen where you will see Firebase configuration, copy the red marked Firebase configuration keys keep it in the notepad or something else. You will need these keys to register in your Ionic 4/Angular 8 project.

Next, we will click on the “database” from the left side navbar. Then, look for Realtime Database and click on the “create database” button.

It will open the security rules modal popover, select “start in test mode” option. Remember we are setting up these rules fro testing purpose. In real world app be careful about database rules.

Now, we are all set to use the Firebase Real-time Database.

2. Create Ionic 4/Angular Project

Run the following command to generate a new Ionic 4/Angular project.

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

Choose blank or which ever template you would like to choose from the Ionic’s template list.

? Starter template: 
  tabs         | A starting project with a simple tabbed interface 
  sidemenu     | A starting project with a side menu with navigation in the content area 
❯ blank        | A blank starter project 
  my-first-app | An example application that builds a camera with gallery 
  conference   | A kitchen-sink application that shows off all Ionic has to offer

Head over to the Ionic 4 Firebase project folder.

cd ionic-firebase-setup

Run the following command to install lab mode.

npm i @ionic/lab --save-dev

Start the Ionic 4 app.

ionic serve -l

3. Install Firebase Package in Ionic 4/Angular App

We need to install the Firebase library to set up Firebase in our Ionic 4/Angular app. Run the following command in the terminal.

npm install @angular/fire
4. Configure Firebase Config Keys in Ionic 4

In this step, we will register the Firebase config rules inside the
environment.prod.ts (production environment) and environment.ts file, you can find these files in the src > environments folder.

Add the following code inside the environment.prod.ts file.

export const environment = {
  production: true,
  firebaseConfig: {
    apiKey: "<your-api-key>",
    authDomain: "<your-auth-domain>",
    databaseURL: "<your-database-url>",
    projectId: "<your-cloud-firestore-project>",
    storageBucket: "<your-storage-bucket>",
    messagingSenderId: "<your-sender-id>",
    appId: "<your-app-id>",
    measurementId: "<your-measurement-id>"
  }
};

Place the following code inside the environment.ts file.

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "<your-api-key>",
    authDomain: "<your-auth-domain>",
    databaseURL: "<your-database-url>",
    projectId: "<your-cloud-firestore-project>",
    storageBucket: "<your-storage-bucket>",
    messagingSenderId: "<your-sender-id>",
    appId: "<your-app-id>",
    measurementId: "<your-measurement-id>"
  }
};
5. Import and Register Firebase in AppModule

Lastly, go to app.module.ts file. Here import and register Firebase services along with that also inject Firebase config keys with the AngularFireModule.initializeApp() method.

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';

//  firebase imports, remove what you don't require
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { AngularFireStorageModule } from '@angular/fire/storage';

// environment
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AngularFireStorageModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

6. Conclusion

That’s it for now, finally we have learned how to set up Firebase in an Ionic 4/Angular 8 app. Now, you can connect your Ionic app with Firebase Realtime database and enjoy building it.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Build an Ionic 5 CRUD App with SQLite Database

How to Build an Ionic 5 CRUD App with SQLite Database

In this Ionic 5 SQLite Database tutorial, we will learn how to create Ionic 5 Angular CRUD application and implement SQLite Native plugin to store the data in the SQLite Database. We will create the Create, Read, Update and Delete operation to manage the data in the database. Learn to load the dummy data from the sql database file using HttpClient service.

In this tutorial, we will learn how to create Ionic 5 Angular CRUD application and implement SQLite Native plugin to store the data in the SQLite Database. We will create the Create, Read, Update and Delete operation to manage the data in the database. Moreover, we will also learn to load the dummy data from the sql database file using HttpClient service.

SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database. It is embedded in android by-default. So, there is no need to perform any database setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is displayed in the logcat. For displaying data on the spinner or listview, move to the next page. Storing data on a user device is an essential topic that we are going to cover in this Ionic 4 hybrid mobile app tutorial.

Table of Contents

  • Prerequisite
  • Install New Ionic 5 Application
  • Adding Fake SQL Data
  • Configure Routes
  • Install & Configure Packages – sqlite, sqlite-porter, cordova-sqlite-storage
  • Create CRUD Service with SQLite
  • Implement Reactive Forms in Ionic 5
  • Add, Display & Delete Data from SQLite Database
  • Update Data from SQLite Database
  • Run Ionic App in Device
  • Conclusion
Ionic 5 SQLite Database Example

Prerequisite

We must have following tools, frameworks, and packages to get started with this tutorial.

  • Latest Node
  • Ionic CLI
  • Ionic 5
  • Angular
  • Firebase FCM
  • Postman
  • Text Editor
  • @ionic-native/sqlit
  • Cordova SQLite Storage

Follow this tutorial on: How to Download and Install Node.js and npm

Install New Ionic 4 Application

We are going to work with Ionic 4 Native SQLite plugin, and It is a robust plugin for storing the data and primarily used with Ionic framework. It works on the same SQL pattern tables and rows. We write SQL queries to fetch the data from the database. It works on the user’s device memory, and the good thing is It doesn’t have storage limitation to store the data.

Install the latest version of Ionic CLI and Cordova globally installed on your device, run the below command.

sudo npm install -g cordova ionic

Run the following command to verify the Ionic CLI version.

ionic -v

# 5.4.15

Run the following command to create a brand new blank Ionic 4 Angular project.

ionic start ionic-sqlite-app blank --type=angular

Go inside the Ionic project directory.

cd ionic-sqlite-app

Start the app in the browser.

ionic serve --lab
Adding Fake SQL Data

Let’s add some dummy data, and we can add even data in JSON format; however, in this article, i will teach how to add SQL data.

Create a SQL file inside assets/dump.sql folder and insert the following data in it.

CREATE TABLE IF NOT EXISTS songtable(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    artist_name TEXT, 
    song_name TEXT
);

INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (1, 'Justin Bieber', 'Yummy');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (2, 'Jonas Brothers', 'What A Man Gotta Do');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (3, 'Life Is Good', 'Future');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (4, 'Lauv', 'Tattoos Together');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (5, 'Heavy Steppers', 'Whateva');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (6, 'DigDat 2020', 'Ei8ht Mile');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (7, 'Blackbear', 'me & ur ghost');
INSERT or IGNORE INTO songtable(id, artist_name, song_name) VALUES (8, 'Hailee Steinfeld', 'Wrong Direction');

As you can see, we defined the SQL table, in which there is an ID which is set to auto-increment. The artist_name and song_name values belong to the string data type.

Configure Routes

Now, we require to generate a page. On this page, we show the song data, and a user can perform the update operation as well. Secondly, we will make the small change for the song route in the app routing file.

Run the command from terminal to create the page.

ng generate page song

Open the app-routing.module.ts file and add the following code in it.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)},
  {
    path: 'song/:id',
    loadChildren: () => import('./song/song.module').then( m => m.SongPageModule)
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})

export class AppRoutingModule { }

We have completed almost every configuration required for this tutorial; let’s start writing the core logic for storing data in the SQLite database.

Install & Configure Packages – sqlite, sqlite-porter, cordova-sqlite-storage

Run the following commands to install the required packages such as sqlite-porter, cordova-sqlite-storage, @ionic-native/sqlite.

$ npm install @ionic-native/sqlite
$ ionic cordova plugin add cordova-sqlite-storage

$ npm install @ionic-native/sqlite-porter
$ ionic cordova plugin add uk.co.workingedge.cordova.plugin.sqliteporter

This SQLite Porter plugin is used to import and export to and from a SQLite database using either SQL or JSON.

Next, import and register the above plugins in the application’s main app module file, this will allow us to access all the methods and services of the SQLite Database.

Don’t forget to add the HttpClientModule as we will be making the HTTP request to render the data locally from the SQL data file.

Open app.module.ts file and place the following code inside of it.

// 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';

// plugins
import { SQLite } from '@ionic-native/sqlite/ngx';
import { HttpClientModule } from '@angular/common/http';
import { SQLitePorter } from '@ionic-native/sqlite-porter/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    SQLite,
    SQLitePorter,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}
Create CRUD Service with SQLite

Run the following command to create a song class file.

ng g class services/song

Define the data types for the Song object in services/song.ts file.

export class Song {
  id: number;
  artist_name: string;
  song_name: string;
}

Angular service keeps all the essential functions and methods at one place that we don’t want to define in our application repetitively. Create a service file inside the service folder by using the command below.

ng generate service services/db

Open the services/db.service.ts file replace with the following code.

// db.service.ts

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Song } from './song';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { SQLitePorter } from '@ionic-native/sqlite-porter/ngx';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';

@Injectable({
  providedIn: 'root'
})

export class DbService {
  private storage: SQLiteObject;
  songsList = new BehaviorSubject([]);
  private isDbReady: BehaviorSubject<boolean> = new BehaviorSubject(false);

  constructor(
    private platform: Platform, 
    private sqlite: SQLite, 
    private httpClient: HttpClient,
    private sqlPorter: SQLitePorter,
  ) {
    this.platform.ready().then(() => {
      this.sqlite.create({
        name: 'positronx_db.db',
        location: 'default'
      })
      .then((db: SQLiteObject) => {
          this.storage = db;
          this.getFakeData();
      });
    });
  }

  dbState() {
    return this.isDbReady.asObservable();
  }

  fetchSongs(): Observable<Song[]> {
    return this.songsList.asObservable();
  }

    // Render fake data
    getFakeData() {
      this.httpClient.get(
        'assets/dump.sql', 
        {responseType: 'text'}
      ).subscribe(data => {
        this.sqlPorter.importSqlToDb(this.storage, data)
          .then(_ => {
            this.getSongs();
            this.isDbReady.next(true);
          })
          .catch(error => console.error(error));
      });
    }

  // Get list
  getSongs(){
    return this.storage.executeSql('SELECT * FROM songtable', []).then(res => {
      let items: Song[] = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) { 
          items.push({ 
            id: res.rows.item(i).id,
            artist_name: res.rows.item(i).artist_name,  
            song_name: res.rows.item(i).song_name
           });
        }
      }
      this.songsList.next(items);
    });
  }

  // Add
  addSong(artist_name, song_name) {
    let data = [artist_name, song_name];
    return this.storage.executeSql('INSERT INTO songtable (artist_name, song_name) VALUES (?, ?)', data)
    .then(res => {
      this.getSongs();
    });
  }

  // Get single object
  getSong(id): Promise<Song> {
    return this.storage.executeSql('SELECT * FROM songtable WHERE id = ?', [id]).then(res => { 
      return {
        id: res.rows.item(0).id,
        artist_name: res.rows.item(0).artist_name,  
        song_name: res.rows.item(0).song_name
      }
    });
  }

  // Update
  updateSong(id, song: Song) {
    let data = [song.artist_name, song.song_name];
    return this.storage.executeSql(`UPDATE songtable SET artist_name = ?, song_name = ? WHERE id = ${id}`, data)
    .then(data => {
      this.getSongs();
    })
  }

  // Delete
  deleteSong(id) {
    return this.storage.executeSql('DELETE FROM songtable WHERE id = ?', [id])
    .then(_ => {
      this.getSongs();
    });
  }
}

Import required API at the top part of the database service file.

The Song class is imported, which allows us to define the data type for the Song object.

The SQLite database is created when the app is ready using the Platform API. In response, we are also loading the dummy song data by calling the getFakeData() method.

To get the current database state, we imported RxJS BehaviorSubject and Observable properties and can extract the current database state by merely subscribing to them.

The getFakeData() method renders the fake data from the dump.sql file. We access the dummy data by making the Http GET request and then subscribe to the response and also setting the database state to true.

The executeSql() function allows us to make SQL queries to interacts with the SQL database, and we are using it to Get, Send, Update, or Delete the data from the storage.

Implement Reactive Forms in Ionic 4

Working with Reactive Forms in Ionic requires to import and register ReactiveFormsModule API in every Ionic page that we are going to work with. For example, in this tutorial, we will need the form in the Home and Song page to add or update the data.

Open your home.module.ts and song.module.ts files and import ReactiveFormsModule in the header part and register this API in the imports array.

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

@NgModule({
  imports: [
    ReactiveFormsModule,
    FormsModule
  ]
})
Add, Display & Delete Data from SQLite Database

Now, we will learn how to fetch, add and remove data from the SQLite database. Open the home.page.ts file and import the following services in the header section.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from "@angular/forms";
import { DbService } from './../services/db.service';
import { ToastController } from '@ionic/angular';
import { Router } from "@angular/router";

The FormGroup and FormBuilder are used to create the Reactive Form to get the user entered data.

  constructor(
    private db: DbService,
    public formBuilder: FormBuilder,
    private toast: ToastController,
    private router: Router
  ) { }

Inject the services in the constructor. Define Reactive Form by declaring the mainForm: FormGroup, to display the song data, also declare Data array.

mainForm: FormGroup;
Data: any[] = []

To show the data, we need to use the DbService that we injected in the constructor. Set the method in the ngOnInit life cycle hook.

Check the database state if its true then render the song list using the fetchSongs() method.

The mainForm is the main object that initiates the main form to add the data in the SQLite database.

ngOnInit() {
  this.db.dbState().subscribe((res) => {
    if(res){
      this.db.fetchSongs().subscribe(item => {
        this.Data = item
      })
    }
  });

  this.mainForm = this.formBuilder.group({
    artist: [''],
    song: ['']
  })
}

The storeData() method stores the data in the storage when a user clicks on the submit button.

storeData() {
  this.db.addSong(
    this.mainForm.value.artist,
    this.mainForm.value.song
  ).then((res) => {
    this.mainForm.reset();
  })
}

Here is the method to delete the data from the SQL database; we also used the Ionic Toast service to display the data delete the message when data is removed.

deleteSong(id){
  this.db.deleteSong(id).then(async(res) => {
    let toast = await this.toast.create({
      message: 'Song deleted',
      duration: 2500
    });
    toast.present();      
  })
}

Here is the completed code in the src/home.page.ts file.

// home.page.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from "@angular/forms";
import { DbService } from './../services/db.service';
import { ToastController } from '@ionic/angular';
import { Router } from "@angular/router";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {
  mainForm: FormGroup;
  Data: any[] = []

  constructor(
    private db: DbService,
    public formBuilder: FormBuilder,
    private toast: ToastController,
    private router: Router
  ) { }

  ngOnInit() {
    this.db.dbState().subscribe((res) => {
      if(res){
        this.db.fetchSongs().subscribe(item => {
          this.Data = item
        })
      }
    });

    this.mainForm = this.formBuilder.group({
      artist: [''],
      song: ['']
    })
  }

  storeData() {
    this.db.addSong(
      this.mainForm.value.artist,
      this.mainForm.value.song
    ).then((res) => {
      this.mainForm.reset();
    })
  }

  deleteSong(id){
    this.db.deleteSong(id).then(async(res) => {
      let toast = await this.toast.create({
        message: 'Song deleted',
        duration: 2500
      });
      toast.present();      
    })
  }

}

Open the home.page.html file and place the following code inside of it. It contains the form and song data list.

// home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>Ionic 4 SQLite CRUD Example</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list lines="full">
    <form [formGroup]="mainForm" (ngSubmit)="storeData()">
      <ion-item>
        <ion-label position="floating">Artist name</ion-label>
        <ion-input formControlName="artist" type="text" required></ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Song name</ion-label>
        <ion-input formControlName="song" type="text" required>
        </ion-input>
      </ion-item>

      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full" expand="block">
            Add Song
          </ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>

    <ion-list>
    <ion-list-header>
      Songs
    </ion-list-header>

    <ion-item lines="inset" *ngFor="let data of Data">
      <ion-label>
        <h5>{{data.artist_name}}</h5>
        <p>{{data.song_name}}</p>
      </ion-label>

      <div class="item-note" item-end>
        <ion-icon name="create" style="zoom:2.0" [routerLink]="['/song/', data.id]"></ion-icon>        
        <ion-icon name="trash" style="zoom:2.0" (click)="deleteSong(data.id)"></ion-icon>
      </div>
    </ion-item>
  </ion-list>
</ion-content>

We declared the click method and passed the deleteSong(id) method with the data-id.

Update Data from SQLite Database

Open the song.page.html file and replace with the following code.

// song.page.html

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

<ion-content>
  <ion-list lines="full">
    <form [formGroup]="editForm" (ngSubmit)="saveForm()">
      <ion-item>
        <ion-label position="floating">Artist name</ion-label>
        <ion-input formControlName="artist_name" type="text" required></ion-input>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Song name</ion-label>
        <ion-input formControlName="song_name" type="text" required>
        </ion-input>
      </ion-item>

      <ion-row>
        <ion-col>
          <ion-button type="submit" color="primary" shape="full" expand="block">
            Update
          </ion-button>
        </ion-col>
      </ion-row>
    </form>
  </ion-list>
</ion-content>

Open the song.page.ts file and replace with the following code.

// song.page.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from "@angular/forms";
import { DbService } from './../services/db.service'
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: 'app-song',
  templateUrl: './song.page.html',
  styleUrls: ['./song.page.scss'],
})
export class SongPage implements OnInit {
  editForm: FormGroup;
  id: any;

  constructor(
    private db: DbService,
    private router: Router,
    public formBuilder: FormBuilder,
    private actRoute: ActivatedRoute
  ) {
    this.id = this.actRoute.snapshot.paramMap.get('id');

    this.db.getSong(this.id).then(res => {
      this.editForm.setValue({
        artist_name: res['artist_name'],
        song_name: res['song_name']
      })
    })
  }

  ngOnInit() {
    this.editForm = this.formBuilder.group({
      artist_name: [''],
      song_name: ['']
    })
  }

  saveForm(){
    this.db.updateSong(this.id, this.editForm.value)
    .then( (res) => {
      console.log(res)
      this.router.navigate(['/home']);
    })
  }

}

Set the form state when the Ionic page is loaded by using the getSong() method, it takes id as a parameter. We are extracting the song id using the ActivatedRoute API. The updateSong() method takes the song object and id to update the data in the SQLite database.

Run Ionic App in Device

To run the app in the Android device we need to use the following commands.

ionic cordova platform add android
ionic cordova run android --livereload
Conclusion

We have completed the Ionic 5 SQLite Database tutorial, in this tutorial, we learned how to create a CRUD application from scratch and store the data in the SQLite database. We learned to load the fake data from the SQL file locally using the HTTPClient API.

I hope you loved this tutorial and share it with others. You can get the complete code of this tutorial on this GitHub repository.

Push Notifications with Ionic 4 and Firebase Cloud Messaging

Push Notifications with Ionic 4 and Firebase Cloud Messaging

Learn how to create and send push notifications from Firebase Cloud Messaging to Ionic app. We will use Ionic 4 Cordova native FCM plugin to receive push notification in an Ionic 4 app. Learn how to send push notifications from Firebase and receive notification in an Ionic app.

In this step by step tutorial, we will learn how to create and send push notifications from Firebase Cloud Messaging to Ionic app. We will use Ionic 4 Cordova native FCM plugin to receive push notification in an Ionic 4 app.

A push notification is a message that shows up on a user’s mobile device. App owners can publish push notification at any time and send it to the user’s device.

Push notifications seem similar to SMS or text messages and mobile alerts. However, they only received by users who have installed your app. Almost every mobile platform supports push notifications such as iOS, Android, Fire OS, Windows, and BlackBerry.

Push notifications provide you updates, be it:

  • Latest offers to boost sales
  • Latest sports scores and news
  • Reports about traffic and weather
  • Flight check-in, change, and connection information
Prerequisite

To get started with this Ionic push notification tutorial, we must have the following tools, frameworks, and packages in our arsenal.

  • Latest Node
  • Ionic 4
  • Angular 8
  • Firebase FCM
  • Postman
  • Text Editor
  • Cordova
  • Ionic 4 Cordova Native FCM

If you do not have Node.js installed on your device then follow this tutorial on: How to Download and Install Node.js and npm

Firebase Setup for Android

To set up Firebase for Android, head over to console.firebase.google.com and create a Firebase project.

Next, a full-screen pop up appears on your screen, enter your project name in the input field and click on the continue button.

In the second screen, you will see Google analytics features you can enable them and click on the create project button.

In the dashboard, you will have options to set up Firebase account for iOS, Android, Web, and Unity. Click on the Android button, and you will be redirected to the given screen.

Next, we will add Firebase to our Android app.

To register the app add the Android package name in the input field. For instance, we entered com.positronx.pushnotification then provided the app’s nickname (same as Ionic project name); however, its an optional value. Then click on the Register app button.

Next, you will see the following screen that allows you to Download the config file, which is used to run the mobile app in the Android Studio or emulator.

Click on the Download google-services.json file. We have to add this file to the based folder of our Ionic app.

Click on the next button unless you reach to the last screen that can be skipped.

We have successfully created the Firebase application for Android platform.

Create Ionic 4 Push Notification App

Make sure you have the latest version of Ionic CLI and Cordova globally installed on your device, if not use the below command.

sudo npm install -g cordova ionic

Check out the version of Ionic by running the following command.

ionic -v

# 5.4.15

Use command to update Ionic and Cordova.

sudo npm update -g cordova ionic

Run the following command to create a brand new blank Ionic 4 Firebase push notification app.

ionic start ionic-firebase-push-notification blank

Get inside the project folder.

cd ionic-firebase-push-notification

Run the following command in the terminal to install the lab plugin as a dev dependency.

npm install --save-dev @ionic/lab

Run the command to start the app in the browser, we can see app in iOS and Android mode.

ionic serve -l

Install & Configure Ionic 4 Cordova Native FCM Plugin

Now, we type the below command in the terminal to Install Google Firebase Cloud Messaging Cordova Push Plugin and Ionic Native FCM plugin.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated

FCM offers basic functionality for Firebase Cloud Messaging (FCM) and It supports iOS and Android.

npm install @ionic-native/fcm

Open your Ionic project and head over to the config.xml file. Here you can see the widget id “com.positronx.pushnotification” that carries the unique identification of your push notification app, here you have to add the package name that we defined in the Firebase.

This time we will inject FCM service to enable the Push notification service in our Ionic app via Firebase FCM, go to app.module.ts file and add the following code in the main app module file.

// 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';

// FCM
import { FCM } from '@ionic-native/fcm/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    FCM,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

We imported FCM plugin and register in the providers array.

Push Notification Implementation in Ionic 4 with Firebase

Now, we will implement push notification in our Ionic 4 Cordova app through Firebase Cloud Messaging.

Place the following code in the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { FCM } from '@ionic-native/fcm/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})

export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private fcm: FCM
  ) {
    this.initializeApp();
  }

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

      // subscribe to a topic
      // this.fcm.subscribeToTopic('Deals');

      // get FCM token
      this.fcm.getToken().then(token => {
        console.log(token);
      });

      // ionic push notification example
      this.fcm.onNotification().subscribe(data => {
        console.log(data);
        if (data.wasTapped) {
          console.log('Received in background');
        } else {
          console.log('Received in foreground');
        }
      });      

      // refresh the FCM token
      this.fcm.onTokenRefresh().subscribe(token => {
        console.log(token);
      });

      // unsubscribe from a topic
      // this.fcm.unsubscribeFromTopic('offers');

    });
  }
}

We imported FCM API from ‘@ionic-native/fcm/ngx’ and Router from ‘@angular/router’.

Inject FCM and Router services in the constructor.

We can access to subscribeToTopic method via FCM package and subscribe to a topic, the subscribeToTopic() takes the topic name as a parameter.

The fcm.getToken() method returns a token of a push notification, and we are showing the token in the console.

The fcm.onNotification() method returns a push notification from Firebase Cloud Messaging.

The fcm.onTokenRefresh() method allows refreshing the Firebase Cloud Messaging (FCM) token.

Use unsubscribeFromTopic() method to unsubscribe from a topic from FCM.

Sending and Receiving Push Notification in Ionic 4 via FCM

In this step, we will create the project build; let’s run the below command to add the Android platform in Ionic app.

ionic cordova platform add android

In this step, we will add the google-services.json in the root of our project and also inside the platform/android folder file that we downloaded from Firebase FCM. This step is crucial, and it makes communication between the Ionic app and Firebase.

Run the Ionic app in the Android device by using the following command.

ionic cordova run android --livereload

We used the --livereload tag. It automatically creates the build as soon as it noticed any change in the application files.

Firebase Cloud Messaging Example

Go to your Firebase dashboard click on Grow > Cloud Messaging, we define Firebase Notification here, add the notification title, text even you can pass the notification image here.

Click on the ‘Send test message’ button, and it will open a popup where you have to define the Firebase Cloud Messaging token to send push notification to the Ionic 4 app.

Type chrome://inspect in the address bar, then select the inspect mode there you can see the Firebase push notification token that we will need in the next step.

We have done all the formalities, and now we will hit on the Test button to send a test notification.

Conclusion

The Ionic 4 Firebase FCM Push Notification Tutorial is over; in this tutorial, we have learned how to send push notifications from Firebase and receive notification in an Ionic app.

You can get the complete code of this tutorial on this GitHub repository.

Push Notification using Ionic 4 and Firebase Cloud Messaging

Push Notification using Ionic 4 and Firebase Cloud Messaging

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM)

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM). We will use Ionic 4 Cordova native FCM plugin for receiving a push notification and using Firebase API for sending push notification from the Postman.

Table of Contents:

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
4.10.3

1. Setup and Configure Google Firebase Cloud Messaging

Open your browser then go to Google Firebase Console then login using your Google account.

Next, click on the Add Project button then fill the Project Name with Ionic 4 FCM and check the terms then click Create Project button.

After clicking the continue button you will redirect to the Project Dashboard page. Click the Gear Button on the right of Project Overview then click Project Settings. Click the Cloud Messaging tab the write down the Server Key and Sender ID for next usage in the API and Ionic 4 App. Next, back to the General tab then click the Android icon in your Apps to add Android App.

Fill the required fields in the form as above then click Register App button. Next, download the google-services.json that will use in the Ionic 4 app later. Click next after download, you can skip Add Firebase SDK by click again Next button. You can skip step 4 if there’s no App creating on running yet.

2. Create a new Ionic 4 App

To create a new Ionic 4 App, type this command in your terminal.

ionic start ionic4-push blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Install the free Ionic Appflow SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-push

As usual, run the Ionic 4 App for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 App with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

3. Add Ionic 4 Cordova Native FCM Plugin

To install Ionic 4 Cordova Native Firebase Message Plugin, type this command.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
npm install @ionic-native/fcm

Next, open and edit src/app/app.module.ts then add this import.

import { FCM } from '@ionic-native/fcm/ngx';

Add to @NgModule providers.

providers: [
&nbsp; StatusBar,
&nbsp; SplashScreen,
&nbsp; FCM,
&nbsp; { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],

Next, open and edit src/app/app.component.ts then add this import.

import { FCM } from '@ionic-native/fcm/ngx';
import { Router } from '@angular/router';

Inject FCM and Router module to the constructor.

constructor(
&nbsp; private platform: Platform,
&nbsp; private splashScreen: SplashScreen,
&nbsp; private statusBar: StatusBar,
&nbsp; private fcm: FCM,
&nbsp; private router: Router
) {
&nbsp; this.initializeApp();
}

Inside platform ready of initializeApp function, add a function to get FCM token then print out to the browser console.

this.fcm.getToken().then(token => {
&nbsp; console.log(token);
});

Add this function to refresh the FCM token.

this.fcm.onTokenRefresh().subscribe(token => {
&nbsp; console.log(token);
});

Add this function to receive push notification from Firebase Cloud Messaging.

this.fcm.onNotification().subscribe(data => {
&nbsp; console.log(data);
&nbsp; if (data.wasTapped) {
&nbsp; &nbsp; console.log('Received in background');
&nbsp; &nbsp; this.router.navigate([data.landing_page, data.price]);
&nbsp; } else {
&nbsp; &nbsp; console.log('Received in foreground');
&nbsp; &nbsp; this.router.navigate([data.landing_page, data.price]);
&nbsp; }
});

Above example of receiving a push notification from FCM will redirect to the other page with params of data. For that, next, we have to add a new page by type this command.

ionic g page second

Next, modify src/app/app-routing.module.ts then change the new page route.

const routes: Routes = [
&nbsp; { path: '', redirectTo: 'home', pathMatch: 'full' },
&nbsp; { path: 'home', loadChildren: './home/home.module#HomePageModule' },
&nbsp; { path: 'second/:price', loadChildren: './second/second.module#SecondPageModule' },
];

Next, open and edit src/app/second/second.page.ts then add this import.

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

Inject that module to the constructor.

constructor(private route: ActivatedRoute) { }

Add a variable for hold data from router parameters.

price: any = '';

Add this line to get data from the router parameters.

constructor(private route: ActivatedRoute) {
&nbsp; this.price = this.route.snapshot.params['price'];
}

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

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-title>Second</ion-title>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <ion-card>
&nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-title>Congratulation!</ion-card-title>
&nbsp; &nbsp; </ion-card-header>

&nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; You get price from our sponsor:
&nbsp; &nbsp; &nbsp; <h2>{{price}}</h2>
&nbsp; &nbsp; </ion-card-content>
&nbsp; </ion-card>
</ion-content>

If you plan to send push notification to the group of topic, add this lines inside the platform ready.

this.fcm.subscribeToTopic('people');

To unsubscribe from topic, add this line.

this.fcm.unsubscribeFromTopic('marketing');

4. Run and Test Sending and Receiving Push Notification

Before running this Ionic 4 app, we have to copy the downloaded google-services.json file to the root of the project. Type this command to add the Android platform.

ionic cordova platform add android

Next, copy the google-services.json to the platform/android/ directory.

cp google-services.json platform/android/

Next, run the Ionic 4 App to the Android device by type this command.

ionic cordova run android

After the app running on the device, check the console from the Google Chrome by type this address chrome://inspect then choose the inspect link. You should take to the browser inspector, just change to the console tab.

As you can see above, you can take and write down the FCM token for use by Postman. Next, open the Postman application from your computer. Change the method to POST and add this address [https://fcm.googleapis.com/fcm/send](https://fcm.googleapis.com/fcm/send "https://fcm.googleapis.com/fcm/send"). On the headers, add this key Content-Type with value application/json and Authorization with value key=YOUR_FIREBASE_KEY....

Next, add this JSON data to the RAW body.

{
&nbsp; "notification":{
&nbsp; &nbsp; "title":"Ionic 4 Notification",
&nbsp; &nbsp; "body":"This notification sent from POSTMAN using Firebase HTTP protocol",
&nbsp; &nbsp; "sound":"default",
&nbsp; &nbsp; "click_action":"FCM_PLUGIN_ACTIVITY",
&nbsp; &nbsp; "icon":"fcm_push_icon"
&nbsp; },
&nbsp; "data":{
&nbsp; &nbsp; "landing_page":"second",
&nbsp; &nbsp; "price":"$3,000.00"
&nbsp; },
&nbsp; &nbsp; "to":"eadego-nig0:APA91bEtKx9hv50lmQmfzl-bSDdsZyTQ4RkelInfzxrPcZjJaSgDmok3-WQKV5FBu9hrMrkRrcCmf3arkGSviGltg5CyC2F9x1J2m0W7U8PxJ3Zlh7-_tL6VcFdb76hbaLIdZ-dOK15r",
&nbsp; &nbsp; "priority":"high",
&nbsp; &nbsp; "restricted_package_name":""
}

If you want to send by topics recipients, change the value of to to topics/people. Next, click the send button and you should see this response.

{
&nbsp; &nbsp; "multicast_id": 7712395953543412819,
&nbsp; &nbsp; "success": 1,
&nbsp; &nbsp; "failure": 0,
&nbsp; &nbsp; "canonical_ids": 0,
&nbsp; &nbsp; "results": [
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "message_id": "0:1550632139317442%b73443ccb73443cc"
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; ]
}

And you will see the notification in your Android device background screen.

If you tap on it, it will open the App and redirect to the second page with this view.

That it’s, the example of receiving push notification using Ionic 4 and Firebase Cloud Messaging. You can grab the full source code from our GitHub.