Integrating Firebase into an Ionic app with AngularFire2 part 1

February 23, 2017, 9:10 pm Categories:

Categories

** UPDATED TO IONIC 3**

From building highly scalable NoSQL database structures to providing file storage, push notifications and usage analytics Firebase is a pretty solid choice for developers looking for an online data solution to integrate with their mobile apps.

In this tutorial we're going to focus purely on the database aspect of Firebase and build a very simple Ionic application for the iOS platform that allows us to perform CRUD (Create, Read, Update & Delete) operations courtesy of the AngularFire2 node package.

Our application will handle movie related data such as:

  • Movie title
  • Classification (I.e. PG, 12, 18)
  • Genre
  • Actors/Actresses
  • Summary
  • Year Released

Nothing terribly complicated but enough to guide us through working with Firebase and AngularFire2.

We'll also be making use of the following Ionic/Angular features:

By the end of this tutorial we should find ourselves with an application that looks something like the following:

Ionic application displaying Firebase data retrieved through AngularFire 2

Now we know what's expected let's make a start with setting up our Firebase environment...

Working with Firebase

Navigate to the Firebase website in your browser and, if already registered with the service, log in to your account (if you're not registered then go ahead and create an account, it's free!)

Once logged in you should see all of your existing projects (if you have any) displayed on your account home page like so:

Firebase projects landing page

Let's begin creating a brand new project by selecting the CREATE NEW PROJECT button and, in the modal window that appears, entering your project name and selecting the Country/region from the drop down menu:

Firebase create project

Once your project has been created you can choose how to add Firebase to your application by simply choosing from the following options:

  • Add Firebase to your iOS app
  • Add Firebase to your Android app
  • Add Firebase to your web app

Go ahead and select the Add Firebase to your web app option as this will provide us with the necessary configuration values to integrate Firebase into our Ionic application regardless of platform (I.e web, iOS or Android):

Choose how Firebase will be added to your app

From the modal window that appears, copy the following configuration keys and values:

  • apiKey
  • authDomain
  • databaseURL
  • storageBucket
  • messagingSenderId

Simply copy but do NOT edit these values as you WON'T be able to connect with your Firebase app without them:

Our completed Firebase database

Once copied paste these configuration keys/values into a text file for safekeeping (we'll use these once we create our Ionic project - which will be a little later on in this tutorial).

With our Firebase project now created we can start setting up the database and importing all required data.

Setting up the Database

There are 2 ways in which we can create a database in Firebase:

  • Manually through adding keys and entering values within the Firebase database console
  • Importing a JSON file with a pre-structured and populated set of keys and values that will represent our database

I always opt for the second approach as I find this quicker, simpler, easier and more efficient when it comes to creating data structures for use with Firebase/NoSQL databases.

In your favourite code editor create the following JSON structure:

{
   "films" : [
      {
      	 "title" : "John Wick",
      	 "summary": "Ex-assassin John Wick takes down the Russian Mafia in New York",
      	 "date" : "2014",
      	 "duration": "97 minutes",
      	 "rating": "15",
      	 "cover" : "none",
      	 "actors" : [
      	    {
      	       "name" : "Keanu Reeves"
      	    },
      	    {
      	       "name" : "Willem Dafoe"
      	    },
      	    {
      	       "name" : "Michael Nyqvist"
      	    },
      	    {
      	       "name" : "Ian McShane"
      	    },               
      	    {
      	       "name" : "John Leguizamo"
      	    },               
      	    {
      	       "name" : "Bridget Moynahan"
      	    },
      	    {
      	       "name" : "Alfie Allen"
      	    },
      	    {
      	       "name" : "Adrianne Palicki"
      	    }
      	 ],				
      	 "genres" : [
      	    {
      	       "name" : "Action"
      	    },
      	    {
      	       "name" : "Thriller"
      	    }
      	 ]
      },
      {
         "title" : "Gladiator",
         "summary": "The general who became a slave, the slave who became a gladiator, the gladiator who defied an empire",
         "date" : "2000",
         "duration": "2hr 29 minutes",
         "rating": "15",
         "cover" : "none",
         "actors" : [
            {
               "name" : "Russell Crowe"
            },
            {
               "name" : "Oliver Reed"
            },
            {
               "name" : "Joaquin Phoenix"
            },
            {
               "name" : "Connie Nielsen"
            },               
            {
               "name" : "Ralf Moeller"
            }
         ],				
         "genres" : [
            {
               "name" : "Action"
            },
            {
               "name" : "Historical"
            }
         ]
      },
      {
         "title" : "Catch me if you can",
         "summary": "Frank Abagnale Jr, master of deception",
         "date" : "2002",
         "duration": "135 minutes",
         "rating": "12",
         "cover" : "none",
         "actors" : [
            {
               "name" : "Tom Hanks"
            },
            {
               "name" : "Leonardo Dicaprio"
            },
            {
               "name" : "Christopher Walken"
            }
         ],				
         "genres" : [
            {
               "name" : "Action"
            },
            {
               "name" : "Thriller"
            }
         ]
      }
   ]
}

This simply contains 3 film entries with the following nested data:

  • actors
  • genres

I've opted for a nested data structure, instead of separating the actors and genres nodes into their own separate collections, as this is more practical when using AngularFire2 (we'll discuss the reasons behind this in the next section).

Be sure to save this JSON file as database.json (we'll now use this to populate the Firebase database).

Return to your Firebase console, select the Database option from the left hand menu and under the Data tab choose the Import JSON option from the menu consisting of 3 vertical dots:

Import JSON into a Firebase database

Select the database.json file you saved a few moments ago and import this into the database:

Import JSON file to Firebase

As stated earlier, we could have created the database manually, from within the Firebase Database console, but importing a pre-populated JSON structure is a far quicker and more efficient method of setting up the data that we need for our project.

Once the database has been populated it should appear like the following (I've taken the liberty of expanding the final node in the database to reveal the keys/values contained within):

Firebase database with films entries

Databases are essentially nothing more than JSON 'trees' within Firebase and are able to be scaled with far more ease than a traditional SQL data structure. This does however require an understanding of best practice approaches, such as denormalisation, and I would advise any developer not already familiar with Firebase to read this document concerning structuring a database.

Now that the database has been populated there's one last step we need to make which concerns the configuration of security rules for access.

Under the Rules tab of the Database panel make the following changes:

Configuring Firebase access rules

Here we simply comment out the default rules and, with the duplicated rules, set the read and write keys to NOT require authentication.

We could, of course, have kept the default rules as:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Then relied on AngularFire2's authentication API to gain access to the database (after setting up the authentication method to use, such as E-mail and Password, under the Authentication section of the Firebase account).

For this tutorial we'll keep it simple though and disallow security rules to be enabled for database access (for a real world project this would NEVER be advisable - for what should be obvious reasons, I.e you do NOT want unauthorised access to your data from any other party).

Now that we've configured the database let's turn our attention towards exploring AngularFire2.

AngularFire2

Thanks to Ionic's use of the underlying Angular framework we can leverage a wide range of node packages for use in our projects.

AngularFire2 is one of those packages and provides developers looking to integrate Firebase into their applications with the following features:

This last point in particular is the "killer" feature of using AngularFire2 - updating the application UI in real-time to reflect any changes that have been made to the Firebase data.

This is actually quite useful as it means we don't have to implement logic to instruct the application UI to refresh itself in order to pick up those changes - AngularFire2 simply handles that for us in the background.

All of which sounds great BUT the package does have some VERY serious limitations:

  • Images are NOT able to be uploaded to Firebase Storage
  • Performing queries across multiple collections (similar to a SQL relational database query) is NOT possible

This, to put it mildly, makes AngularFire2 quite limited in scope for use in major Ionic projects which is unfortunate because it's fairly straightforward to implement and makes synchronising UI changes with updates to Firebase data relatively seamless.

Hopefully the developers of AngularFire2 will be able to resolve these limitations and provide such features in future releases of the software but, until then, we're simply going to focus on working with text based data from our database.

Creating our project

Now that everything has been configured server-side let's get started with actually creating an Ionic project.

Open up a command line window (I.e. Terminal if you're using Mac OS X or the Command Prompt if you're on a Windows platform), navigate to your desired system directory and execute the following command to create a project called moveez:

ionic start moveez blank

Once the project has been created change into the moveez project:

cd moveez

And install the following:

npm install -g typings
npm install angularfire2 firebase --save

We begin with installing the necessary type definitions so that the project compiler will be able to understand and work with the firebase and AngularFire2 packages (which are subsequently installed through the line following that command).

Finally we complete the command line configurations for the project by creating the modals component:

ionic g page modals

With everything now in place let's set up the root module for the Moveez application.

Rooting for Moveez

As with all things Ionic/Angular we need to ensure that any modules required for the functioning of our application are made available to the root module during the bootstrapping/initialisation phase (and also to avoid those helpful but simultaneously annoying error messages from the transpiler when attempting to build our app only to find something has gone a little awry in the process).

Open the moveez/src/app/app.module.ts file and make the following amendments:

  • Import the AngularFireModule
  • Add the Firebase configuration object

All of this should look something like the following (be sure to replace API-KEY-IS-ENTERED-HERE, YOUR-PROJECT-NAME-HERE, YOUR-DATABASE-NAME-HERE, YOUR-STORAGE-BUCKET-NAME-HERE AND YOUR-MESSAGING-SENDER-ID-HERE with the exact values found from the Add Firebase to your Web App configuration that you copied during the latter part of the Working with Firebase section earlier in this tutorial):

import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { AngularFireModule } from 'angularfire2';


export const firebaseConfig = {
  apiKey            : 'API-KEY-IS-ENTERED-HERE',
  authDomain        : 'https://console.firebase.google.com/project/YOUR-PROJECT-NAME-HERE',
  databaseURL       : 'https://YOUR-DATABASE-NAME-HERE.firebaseio.com/',
  storageBucket     : 'gs://YOUR-STORAGE-BUCKET-NAME-HERE.appspot.com',
  messagingSenderId : 'YOUR-MESSAGING-SENDER-ID-HERE'
};


@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    BrowserModule,
    HttpModule,
    AngularFireModule.initializeApp(firebaseConfig)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Save these changes and join me for part 2 of this tutorial where we conclude the development of the Moveez application.

In summary

During this first part of the tutorial we've familiarised ourselves with setting up a Firebase database (understanding the reasoning behind our choice of data structure while doing so), created the basic skeleton for an Ionic project, installed the necessary node packages and type definitions before, finally, configuring our Ionic root module.

It may not seem like much but we've covered a lot of ground in both setting up the server-side environment for our project and creating the foundations for our mobile application.

We'll conclude the development of our project and see how Firebase data can be integrated into an Ionic application using AngularFire2 in part 2 of this tutorial.

If you enjoyed what you've read here then please sign up to my mailing list and, if you haven't done so already, take a look at my e-book: Mastering Ionic for information about working with alternative data storage methods in Ionic.

Tags

Categories

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.

Top