Last update on Wednesday, July 5th 2017

Using Firebase and AngularFire2 in an Ionic Real-Time TODO application

After the previous articles on AWS, a similar technology was left behind: Firebase.
This technology is ******* amazing. So much power that is given to us and you will understand one part of it at the end of this tutorial.
Today we create a Real-Time TODO application using AngularFire2, unlike other traditional TODO apps this one can be edited by multiple people at the same time.
Some years ago this feature was one of my previous employer's target and we vaguely analyzed how we could do this with Angular, Ruby and MongoDB, the whole data lock synchronization, database update and patati and patata.

Nowadays with Firebase, it's all built in for us!

Firebase Setup

It all starts there:

ionic firebase angularfire login

A new project is created:

ionic firebase angularfire create project

Some crucial information are available in the Project settings section:

ionic firebase angularfire project information

Remember this screen, you will need it later.
We can now go to the Database section and contemplate our empty database:

ionic firebase angularfire empty db

In order to access the database without being authenticated in the Ionic application, the access rules will be changed:

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

We start by manually creating a first task in Firebase:

ionic firebase angularfire manually add task

Here we have the root node.
We add one child called tasks and inside this child we add another node which will be an object. This object has a unique ID and a property called name that we set to "Task1".

Ok, we are not here to do all by hands right 😉?

Let's start our Ionic Firebase project!

Let the show begin

As usual some installations:

ionic start ionic-todo-firebase blank
npm install firebase angularfire2 --save

A configuration file is required for AngularFire, this file will be located in src/environments/environment.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: " AIzaSyAN4H-9VmncDG0PfqmuhmHrXuBtvCojT2E",
    databaseURL: "https://todo-firebase-c4298.firebaseio.com/",
    projectId: "todo-firebase-c4298"
  }
};

This information comes from the previous screenshots. If you want to have all the information, you can have it in the Authentication section by clicking the WEB SETUP button.

ionic firebase angularfire project information 2

Great, we can now do some imports and use this file in the app.module.ts, the modifications are as follow:

.
.
.
import { AngularFireDatabase, AngularFireDatabaseModule } from 'angularfire2/database';

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

@NgModule({
  .
  .
  .
  imports: [
    .
    .
    .
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  providers: [
    AngularFireDatabase,
    .
    .
    .
  ]
})

The AngularFire and AngularFireDatabaseModule are required here. There are other modules like AngularFireAuthModule, but that's for the next tutorial 😉.
The AngularFireModule only needs the Firebase configuration file we created earlier.

We can now switch to the home.ts file, our first goal: displaying the tasks.

import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

export class HomePage {
  tasks: FirebaseListObservable<any[]>;

  constructor(public db: AngularFireDatabase) {
    this.tasks = db.list('/tasks');
  }
}

As you have noticed Observables are invading our world and we are going to use them for the tasks, all of them will be stocked in a FirebaseListObservable.

We acquire the AngularFireDatabase Service and stock it into a db property.
Now we have the power, using the list method, we target the tasks. Unlike conventional databases, we don't do "select * from x" or "get all from y".

Firebase's database is path related, which means we can target:

  • /: The root
  • /tasks: The tasks root
  • /tasks/taskId: A simple task
  • /whateverYouWant: Whatever you want

Now that we have our data in the Typescript side, we display it in the home.html:

  <ion-list>

    <ion-item *ngFor="let task of tasks | async">

      <input type="text" [(ngModel)]="task.name">

    </ion-item>

  </ion-list>

An <ion-list> is used here and inside multiple <ion-item> will be created for each task. The async filter is required because we are working with Observables.
Each <ion-item> will display the task in an input, the two-way data binding ngModel will use the task's name.

And we have our first task displayed:

ionic firebase angularfire first task

Now some magic:

ionic firebase angularfire change value console

If we modify the data in the Firebase console it will be updated everywhere and that's ******* awesome.

Doing this with MongoDB would require to listen for every modifications on a collection, then either querying the database again or looking for the right item to update.

Talking about update, let’s add a button to update the tasks in the Ionic application:

      <input type="text" [(ngModel)]="task.name">
      <button item-left ion-button (click)="updateTask(task.$key, task.name)"><ion-icon name="brush"></ion-icon></button>

We need the task’s key or ID and the data that we want to update.

Back to the home.ts:

  updateTask(key, name) {
    this.tasks.update(key, {name: name});
  }

The update method will look for the corresponding key and update the data in our Firebase Database.

More magic:

ionic firebase angularfire add task

Moving now to the Task Removal feature.

Just a button in the home.html file:

      <button item-left ion-button (click)="removeTask(task)"><ion-icon name="remove"></ion-icon></button>

The removeTask method will handle our task has follow:

  removeTask(task) {
    this.tasks.remove(task);
  }

Easy peasy.

ionic firebase angularfire remove task

Our final feature: Task Creation.

Back to the HomePage’s properties:

export class HomePage {
  tasks: FirebaseListObservable<any[]>;
  newTask = {name: ''};
  .
  .
  .
}

The newTask property will be used as a blank task.

<ion-content padding>

  <input type="text" [(ngModel)]="newTask.name">

  <button ion-button (click)="addTask(newTask)"><ion-icon name="add"></ion-icon></button>

  <ion-list>
    .
    .
    .
  </ion-list>

</ion-content>

A button and a text input will be placed above our list of tasks.
The input will modify the newTask’s name property and the button will trigger the addTask method, which is as follow:

  addTask(newTask) {
    this.tasks.push(newTask);
    this.newTask = {name: ''};
  }

The push method will create the task in the Firebase database, then we reset the newTask property.

And Voila!

ionic firebase angularfire add in app task2

If you encounter this error:

Module not found: Error: Can’t resolve ‘promise-polyfill’ in …

You need the following library:

npm install promise-polyfill --save-exact

Conclusion

Firebase Realtime Database is astonishing, it’s almost the equivalent of AngularJS for Database: the Database Two-Way Binding!

By using AngularFire it’s very easy to make basic manipulations like updating, adding or removing information. It all starts with a Firebase configuration file, adding the Modules and Providers then using the AngularFireDatabase Service to make the requests.

If you liked this tutorial, you can learn more on Firebase’s storage, basic authentication, twitter authentication and cloud functions.

Using Firebase and AngularFire2 Basic Authentication in an Ionic application

Adding Twitter Authentication with Firebase in Ionic

Creating an Ionic PWA with Firebase Offline and Service Workers

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven + other free stuff!