Integrating Firebase into an Ionic app with AngularFire2 part 1

Categories

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.

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

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:

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:

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):

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:

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.

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:

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

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):

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:

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).

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):

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.

In the following tutorial I'm going to guide you through using Angular FormBuilder, FormGroup and FormArray modules to dynamically add and remove input fields in forms for your Ionic framework applications...

In the following tutorial we're going to explore how we can synchronise data between a PouchDB database running on an Ionic app and a remote CouchDB database which will be running on our desktop computer.

We'll use the application that we created in part 1 & part 2 of the PouchDB tutorial as a base to build on. If you haven't read that tutorial, and aren't familiar with the code that was used, I suggest you go there now before proceeding with this tutorial...

Let's face it, form validation is one of those tasks rarely enjoyed by developers - particularly with the volume of data checks and requirements that often entails - but thanks to Angular's FormBuilder class validating online forms just got a little easier...