Building Your First Firebase Powered Ionic Framework App

First Published: 2 July 2018
Updated on: 24 July 2019

This is the first post of a 7 post series that will teach you how to build an app using Ionic Framework and Firebase from scratch.

  • Introduction and the Setup Process. => You are here
  • Authentication.
  • Handling Objects.
  • Handling Lists.
  • Firebase Transactions.
  • Firebase Cloud Storage.
  • Firebase Security Rules.

First of all, Thank you!

It means a lot that you trust me enough to guide you through this journey. The goal of this ‘course’ is for you to use the knowledge you have got about the Ionic framework to start building more robust, responsive, interactive applications, using Firebase as your backend.

This course is not going to be very theoretical. Instead, we will build an application together, and I will guide you through the development of the application explaining new concepts as soon as they pop up. (If you find something that you think should be described better in the course, please leave a comment below, I will be glad to see how we can add it).

-Jorge Vergara, Chief Everything Officer, JAVEBRATT

What we will build

In this first lesson, we are going to create an app for managing events. Think about conferences, parties, etc.

Dashboard for Firebase App

The goal of this app is for you to get comfortable with:

  • User authentication.
  • Create, Read, Update, and Delete (CRUD) data.
  • Use Firebase transactions.
  • Take pictures using capacitor.
  • Upload files to Firebase Storage.
  • Understand Security Rules.

You can find the source code for this app in the GitHub Repo.

We’re going to use the regular Web SDK for Firestore in our first application, and later move to AngularFire.

The reason behind this is simple, AngularFire provides wrappers to the Web SDK, so it’s a good idea to know how the Web SDK works.

Make sure your development environment is up to date

Before writing any code, we are going to take a few minutes to install everything you need to be able to build this app, that way you will not have to be switching context between coding and fixing.

The first thing you will do is install node.js.

The second thing you will do is ensure that you have Ionic installed, you will do that by opening your terminal and typing:

npm install -g ionic

Depending on your operating system (mostly if you run on Linux or Mac) you might have to add sudo before the "npm install" command.

Create the App

Now that you installed everything, you are ready to create your new Ionic app.

To do this, go ahead and open your terminal, move to wherever it is that you save your projects and start the app:

cd Development
ionic start event-manager blank --type=angular
cd event-manager

The start command will create a new app, and the --type=angular flag will create an Ionic app using angular as a framework for handling the logic.

The CLI is going to ask you if you want to add Cordova and Ionic Appflow SDK, choose no in both prompts, we’re using Capacitor for the native functionality and we’ll cover everything we need to know about it soon.

If you are new to the terminal, what those commands do is to:

  • Move you into the Development folder.
  • Create a new Ionic app using the blank template and calling it event-manager.
  • Move into the new app’s folder.

From now on, whenever you are going to type something on the command line, it is going to be in your app’s folder unless I say otherwise.

The "npm" packages that come with the project

When you use the Ionic CLI to create a new project, it is going to do many things for you, one of those things is making sure your project has the necessary npm packages it needs.

That means, the start command is going to install all of the requirements and more, here’s what package.json should look like:

"dependencies": {
  "@angular/common": "^7.2.2",
  "@angular/core": "^7.2.2",
  "@angular/forms": "^7.2.2",
  "@angular/http": "^7.2.2",
  "@angular/platform-browser": "^7.2.2",
  "@angular/platform-browser-dynamic": "^7.2.2",
  "@angular/router": "^7.2.2",
  "@ionic-native/core": "^5.0.0",
  "@ionic-native/splash-screen": "^5.0.0",
  "@ionic-native/status-bar": "^5.0.0",
  "@ionic/angular": "^4.1.0",
  "core-js": "^2.5.4",
  "rxjs": "~6.5.1",
  "tslib": "^1.9.0",
  "zone.js": "~0.8.29"
},

Depending on when you read this, these packages might change (specially version numbers) so keep that in mind; also you can always email me at j@javebratt.com if you have any questions/issues/problems with this.

Let’s take a moment to remove the @ionic-native packages, open the terminal and type:

npm rm @ionic-native/core @ionic-native/splash-screen @ionic-native/status-bar

Capacitor has working APIs to replace those plugins so there’s no need to keep them installed anymore.

Don’t forget to go into the app.module.ts and the app.component.ts files and remove all the reference for @ionic-native there.

Install Firebase

Since all we are going to talk about in this book is Firebase, now we need to install… You guessed it! Firebase :)

To install a new package open your Terminal again and run:

npm install firebase --save

That will install the latest version of the Firebase JavaScript SDK, which is what we will use in this first example. (By the way, if you’re using npm 5 you won’t need to add the –save flag.)

Create and Import Pages and services

There’s much cognitive overhead in the brain when you are switching tasks consistently, so we are going to do something a bit different, we are going to do all the setup the app requires before we start writing functionality code.

That way, when it is time to start writing the app’s functionality we can focus on doing that, and we will not have to switch back and forth between functionality and setup.

So we are going to take a moment to create every page and service we are going to use on our app. First, the pages, go ahead and open your terminal and start generating them:

ionic generate page pages/event-create
ionic generate page pages/event-detail
ionic generate page pages/event-list
ionic generate page pages/login
ionic generate page pages/profile
ionic generate page pages/reset-password
ionic generate page pages/signup

The generate page command creates a folder named after the class you created, let’s go into detail with the first one event-create.

ionic generate page event-create will create a folder named event-create, and inside that folder, it will create five files:

event-create.html is the view file, where we are going to write our HTML code, what our users will eventually see.

<ion-header>
  <ion-toolbar> <ion-title></ion-title> </ion-toolbar>
</ion-header>

<ion-content padding> </ion-content>

event-create.module.ts is the module file, in the past, we used to declare and initialize pages in app.module.ts, Angular splitting and lazy loading. Meaning each page gets its module declaration file, this way, instead of loading every page of the app when our users are launching it, we only load the home page, and then we can load each page as we need them, instead of all at once.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

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

import { EventCreatePage } from './event-create.page';

const routes: Routes = [
  {
    path: '',
    component: EventCreatePage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  declarations: [EventCreatePage]
})
export class EventCreatePageModule {}

You do not need to mess with that file, and it is a trimmed down version of what we have in app.module.ts only for this page.

event-create.scss is a blank style file, where we will be making our apps “prettier.”

Also, event-create.ts is our class, where we are going to be declaring all the functionality the EventCreate class will have.

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

@Component({
  selector: 'app-event-create',
  templateUrl: './event-create.page.html',
  styleUrls: ['./event-create.page.scss']
})
export class EventCreatePage implements OnInit {
  constructor() {}

  ngOnInit() {}
}

And lastly, it creates a event-create.page.specs.ts that is used for testing purposes:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { EventCreatePage } from './event-create.page';

describe('EventCreatePage', () => {
  let component: EventCreatePage;
  let fixture: ComponentFixture<EventCreatePage>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [EventCreatePage],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EventCreatePage);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

If you have any questions about the files that we generated there, you can email me.

After we create all the pages, we are going to create our services, if you do not know what a service is, in the most simple terms services are recipes that know how to create dependencies. That way we can have different services for the various aspects of our code.

For example, we can create an authentication service that handles everything related to authentication, that way when from our page we call the authentication’s service login() function and our page does not care how the service gets it to work, it only cares that it works.

For this application, we will need three services, one for authentication, one to handle all the event management, and one service to manage the user’s profile.

ionic generate service services/user/auth
ionic generate service services/user/profile
ionic generate service services/event/event

Each time you use the generate service command, the Ionic CLI will do a few things for you, let’s examine one of those services to see what got created.

When you run ionic generate service services/user/auth the CLI is going to create a folder called services/user, and that folder will have a file called auth.service.ts here’s what you will see in auth.service.ts.

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

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor() {}
}

It has a few other things, but those are the things we care about, the @Injectable() decorator is what makes it an actual service/module that we can inject into our classes.

Capacitor

We’re going to use Capacitor to communicate with the native layer of the phone, for this app we need to talk to 3 different native parts.

The Statusbar so we can style it depending on the colors of our app, the Splash Screen so we can hide it when our app is ready to run, and the camera so our users can take pictures using our app.

You can find Capacitor’s official docs here, but I’ll do my best to explain every bit we need to get our functionality ready.

Let’s start with understanding a bit more about Capacitor and its role on mobile development. The easiest way to “get it” is by seeing it as a replacement for Cordova.

Capacitor allows you to wrap your app into a native container and helps you communicate with the phone’s native capabilities. You can use it to create a native build of your application (iOS and Android).

Configuring Capacitor

The first thing we need to do to ‘activate’ capacitor is to enable it through the Ionic CLI, so open your terminal (while inside of the project’s folder) and type:

ionic integrations enable capacitor

It will create the necessary files and install the capacitor packages, one thing to keep in mind, it creates a file called capacitor.config.json where you need to go and edit your appId.

By default it sets it up to be io.ionic.starter, it’s a good idea to change it to something more on-brand. The usual convention is to go with com.myDomainName.myProjectName so I’ll name it com.javebratt.eventManager.

Before adding the android/ios platforms we need to generate a build of our project or else Capacitor will have unexpected errors. Open your terminal and type:

ionic build

That command will generate a build of our application inside the www/ folder which is the folder Capacitor is watching.

> SIDE-NOTE: That command generates a development build, if you want to generate a production build for your application add the --prod flag.

Now we can add our platforms, you can add either iOS or Android by using the commands:

ionic cap add ios
ionic cap add android

Remember that you need XCode installed on a Mac to build for iOS. Once you add your platforms it’s time to sync them and copy over the build to the platform respective folder. You do that by opening up the terminal and typing:

ionic cap sync

Now Capacitor is ready to use, we will cover the Camera plugin in the Firebase Storage chapter, but for now, let’s replace the @ionic-native integration for the Status bar and the Splash Screen.

Open your app.component.ts, replace all Ionic Native references for the plugins and replace them with the Capacitor ones, it should look like this:

import { Component } from '@angular/core';
import { Plugins } from '@capacitor/core';

const { SplashScreen, StatusBar } = Plugins;

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor() {
    this.initializeApp();
  }

  initializeApp() {
    SplashScreen.hide().catch(error => {
      console.error(error);
    });

    StatusBar.hide().catch(error => {
      console.error(error);
    });
  }
}

We’re importing the plugins and then hiding both the status bar and the splash screen, if there’s an error (like if the app is running on the web) we can handle it gracefully without annoying our users.

Right now you should have the skeleton of your app ready, go ahead and run ionic serve in the terminal and make sure it’s running. If it’s not and you can’t figure out why, feel free to shoot me an email and I’ll be more than happy to help you debug what’s going wrong.

Next Steps

When you are ready, move to the next part of the course, there you will initialize your app and create the auth module.

Next Lesson: Firebase Authentication.