Is it a good approach to use firebase once method when retrieving all posts on ionViewWillEnter?

I am retrieving all posts (news) from firebase using the once method and showing it on the home tab (the first tab when the app is launched) :

I am retrieving all posts (news) from firebase using the once method and showing it on the home tab (the first tab when the app is launched) :

get_all_posts(){

this.posts = [];
firebase.database().ref('/posts/').once('value').then(snapshot => {
.... //rest of the code
}
}

This will be fired in the ionViewWillEnter():

ionViewWillEnter(){
this.get_all_posts();
}

In this case, get_all_posts method will be fired everytime the "home" tab is pressed right? which will get all posts again from the DB or for the entire session (from opening the app till closing the app running on the phone)the news retrieved from the first time only will be displayed?

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.

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.