CajaFuerte: Learn how to add Firebase and AngularFire2 to an ionic2 app (Part 3)

Image

Welcome to Part 3 of the series: Build an ionic2 app in 3 weeks! In the last 2 posts we layed the foundation for our new app CajaFuerte and completed the mockup. This week we will cover how to add Firebase and AngularFire2 to an ionic2 app.

From Last Week

To recap, we used the Ionic Super Starter template to get us off the ground quickly and we added FontAwesome in the mix. At the end, we created a new app in ionic.io and made the app available for preview with Ionic View ID: 7a8e133b (go check it out).

The commit below shows the results after completing the mockup for our app

Did you miss Part 1 / Part 2?

If you haven’t read part 1 and part 2, go take a look. It will give you a better idea of how we got here and what we’re trying to accomplish in this series:

  1. CajaFuerte: Online Information Manager App (Part 1):
  2. CajaFuerte: ionic and firebase app (Part 2):

But to refresh your memory, the approach I’m taking on this tutorial series is as if I’m working with a customer who hired me to develop an app and is expecting quick results. I offered my fake customer a prototype before begining development and implementing the actual logic so he can “play” with the design and offer valuable feedback. We’re ahead of schedule by 1 week and our fake customer is very happy with our progress and results :sunglasses:

TL;DR - In a Hurry?

Get the code from this GitHub Repo or test drive the finished mockup in Ionic View ID: 7a8e133b

In this tutorial we will cover

  1. Add Firebase and AngularFire2 to Your app
  2. Add Auth Service
  3. Structure Your Database
  4. Database Rules


1. Add Firebase to Your app

I started this tutorial series with the assumption that you were familiar with Firebase. But if you’re not, don’t worry. Visit the official Firebase documentation on how to Add Firebase to your JavaScript Project and watch the video. It will help understand the following sections.

The first thing we need to do is to create a new project in Firebase and we're gonna call it CajaFuerte

create project

Now click on Add Firebase to your web app icon

create project

You will get your Firebase web app config settings (as shown below). We will use these settings in our ionic2 app

create project

Install NPM packages

We are ready to install the Firebase and AngularFire2 npm packages into our app and to do so, I’m following the official instructions found in the AngularFire2 GitHub repo: Configuring AngularFire2 and Firebase

Execute the following command in your project directory

npm install angularfire2 firebase --save

This will add the following dependencies to your project's package.json file

"angularfire2": "^2.0.0-beta.7",
"firebase": "^3.6.8",

In your app.module.ts file add the reference to AngularFireModule import and the configuration information you obtained before

import { AngularFireModule } from 'angularfire2'; 
export const firebaseConfig = {
  apiKey: "xxxxxxxxxx",
  authDomain: "your-domain-name.firebaseapp.com",
  databaseURL: "https://your-domain-name.firebaseio.com",
  storageBucket: "your-domain-name.appspot.com",
  messagingSenderId: '<your-messaging-sender-id>'
};

Initialize your app, by calling it in the "imports" array in @NgModule

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: []
})
export class AppModule { }

2. Add Auth Service

We’re going to add a service provider for our AngularFire2 Auth logic. Again, I’m following the steps shown by official docs: Configuring AngularFire2 Auth with Ionic2.

The command below will create a new file called AuthService under the providers folder

ionic g provider AuthService
CajaFuerte-app/
├── src/
│   ├── providers
│   │   ├── auth-service.ts

Update the service with the following code

import { Injectable } from '@angular/core';
import { AuthProviders, AngularFireAuth, FirebaseAuthState, AuthMethods } from 'angularfire2';

@Injectable()
export class AuthService {
  private authState: FirebaseAuthState;

  constructor(public auth$: AngularFireAuth) {
    this.authState = auth$.getAuth();
    auth$.subscribe((state: FirebaseAuthState) => {
      this.authState = state;
    });
  }

  get authenticated(): boolean {
    return this.authState !== null;
  }

  signInWithFacebook(): firebase.Promise<FirebaseAuthState> {
    return this.auth$.login({
      provider: AuthProviders.Facebook,
      method: AuthMethods.Popup
    });
  }

  signOut(): void {
    this.auth$.logout();
  }

  displayName(): string {
    if (this.authState != null) {
      return this.authState.facebook.displayName;
    } else {
      return '';
    }
  }
}


Add your service in app.module.ts. Your app should look like this


3. Structure Your Database

Based on Firebase’s official docs, the best practice for data structure is to avoid nesting data. In other words, flatten your data - a process called denormalization. This topic in itself deserves a full series of tutorials, so we’re not going to cover it here. But visit the official docs for more information on the subject.

Here’s how we’re going to structure the data for our app. This approach allows us to have the most efficient data access

cajafuerte-firebase-db:
├── users
│   ├── user-id
│   │   ├── user1
│   │   ├── user2
├── vaults
│   ├── vault-id
│   │   ├── vault1
│   │   ├── vault2


4. Database Rules

When you create a new Firebase project (step 1) it includes the following rules by default

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

It is highly recommented to change the rules to prevent data breaches. You can read more about security from the official docs

These are the rules we'll use for our app

{
  "rules": {
    "vaults": {
      "$vault_id": {
        // Grants read/write access to the users whose vaultid exactly match the key ($vault_id)
        ".read": "root.child('users').child(auth.uid).child('vaultid').val() === $vault_id",
        ".write": "root.child('users').child(auth.uid).child('vaultid').val() === $vault_id",
      }
    },
  	"users": {
      "$uid": {
        ".read": "auth != null && auth.uid === $uid",
        ".write": "auth != null && auth.uid === $uid"
      }
    }
	}
}


Here's our app after we added Firebase, AngularFire2, and Auth service


What’s next?

Next post we’re going to wire all our screens to save our information into our Firebase database.

Until then, have a great weekend! I’ll see you in 3/4 days…


Older posts...

Written by

Get in touch!

Notice any mistakes?
Leave me a message