Angular2 with Firebase

Submitted by admin on Sun, 06/26/2016 - 15:38
Fire

If you have been developing with Angular for some time, you probably have used or have heard about Firebase.

Firebase lets you build real-time applications with very little effort, providing you with a backend technology out of the box that automatically synchronizes every connected device, providing authentication and some other nice services on top of that. It was also recently updated with a full set of new services on top of the real-time database, so right now Firebase consists more or less of :

Real-time database Authentication Cloud messaging Storage Hosting Remote config Test lab Crash reporting Notifications Crash index Dynamic Links Invites Adwords Admob integration

Not all of these services apply to the web, but it’s worth mentioning them here since with Angular2 your target might not exactly be the web so maybe you can get an idea of what you could get from firebase. It’s a very long list of very usefull things..

How much does it cost you might be wondering at this point? It starts with a free plan that can get you going until you have 100 simultaneous connections to the database, which is a pretty good number. You can read the full pricing list here.

Using Firebase with Angular

Previously with Angular1, using Firebase was very popular. At the time the firebase team developed Angularfire to better connect the realtime database with angular. It worked pretty well, and with Angular 2 things are pretty much the same, except the work involved on building this library was significantly less according to the firebase team.

In Angular 2 angularefire2 was created, and is now the library you should be using to build your angular2 applications with firebase.

What is Angularfire2

Angularfire2 is an observable based implementation of the firebase database services that you can directly integrate into Angular2. It uses RxJs and allows you to directly inject database queries (objects or lists) into your templates in a seamless integrated way. It also provides you with authentication wrappers to monitor authentication state in realtime.

Using Angularfire2

Getting started with Angularfire2 is extremely easy. It all starts as always with an npm install

Boilerplating


npm install angularfire2 firebase --save

The second step is to include the firebase typings. Now firebase itself is not providing its own typings so for the moment you have to get them from the angularfire2 repo. You can do this in different ways, but the most common is to just include it in your tsconfig.json file :


"files": [
  "node_modules/angularfire2/firebase3.d.ts"
]

Make sure you are not excluding node_modules in that tsconfig file, if you are and you want to use typings insted of this approach you can find some info in this issue where a link to a typings denition file is given and the steps to include it in your typings.json file.

Right now your editor already knows firebase, it can autocomplete the firebase() object and you should be able to start building the real thing and getting firebase connected to your app.

Bootstrap

The next step is to provide the firebase providers and app connection to your angular bootstrap method so you can inject the angularfire2 service in your components and directly query firebase from there. Open the file where your bootstrap method is (e.g src/main.ts) and specify your firebase configuration.


import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppComponent } from './app/app.component';
import { FIREBASE_PROVIDERS, defaultFirebase } from 'angularfire2';

if (environment.production) {
  enableProdMode();
}

bootstrap(AppComponent, [
  FIREBASE_PROVIDERS,
  // Initialize Firebase app  
  defaultFirebase({
    apiKey: "<your-key>",
    authDomain: "<your-project-authdomain>",
    databaseURL: "<your-database-URL>",
    storageBucket: "<your-storage-bucket>",
  })
]);

So what happened here? Basically what is going on is its providing angular with the information on firebase specifics. If you take a look at the firebase documentation for the web you can see that the initialization of firebase looks very simillar. You provide an API Key, an AuthDomain, a Database URL and a storage bucket. The same thing is given to angular2 bootstrap in the previous example along with the FIREBASE_PROVIDERS.

You can now actually start querying firebase in components! Let’s take a look at how that looks like.

Inject AngularFire

Open the component you want to query the firebase service on. Lets say its the main app component inside src/app/app.component.ts


import { Component } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';

@Component({
  selector: 'app',
  template: `<ul *ngFor="let item of items | async">
    <li class="text">
      {{item.$value}}
    </li>
  </ul>
 `
 })
export class AppComponent {
  items: FirebaseListObservable<any[]>;
  constructor(af: AngularFire) {
    this.items = af.database.list('items');
  }
}

The async pipe will automatically unwrap every item and pass it to the template as they come in and prints out a $value property of every item.

This is the very basics of how to get Firebase and angular2 paying together using angularfire2.

But angularfire2 lets us do more than just this. Let’s explore some more examples.

Using Objects with angularfire2

Firebase lets us do actions on objects by using a FirebaseObjectObservable created by AngularFire.database service. You can find the full documentation on how this is done here

First step is to provide the bootstrap as mentioned before so that you get access to a angularfire service in your components.

Now we are going to get an object instead of a list as we did before, and we do that by calling af.database.object.

Retrieving data


import {Component} from 'angular2/core';
import {AngularFire, FirebaseObjectObservable} from 'angularfire2';

@Component({
  selector: 'app',
  template: `
  <h1>{{ (item | async)?.name }}</h1>
  `,
})
export class AppComponent {
  item: FirebaseObjectObservable<any>;
  constructor(af: AngularFire) {
    this.item = af.database.object('/item');
  }
}

As you can see it looks very much like the previous example with the list but in this case what we get is an object, we pass it to the pipe just like we did before but now we print out a name property instead.

Saving data

You not always want to just print and get things from firebase, you also want to save and update and delete things. Let’s take a look on how you can save something on firebase using angularfire2. This could be done for example on a component that contains a form.


const itemObservable = af.database.object('/item');
itemObservable.set({ name: 'new name!'});

Updating data

Using the update() method


const itemObservable = af.database.object('/item');
itemObservable.update({ age: newAge });

Deleting data

Using the remove() method


const itemObservable = af.database.object('/item');
itemObservable.remove();

Lists work pretty much the same way and you can see them here

Querying in lists

One of the most impressive feature of angularfire2 is queries. Firebase allows you to query lists using some specific syntax but when using angularfire2 you can actually provide observables to these query items, and when those values get updated the query runs and gets the new values back.

You make queries by using a query object in the FirebaseListObservable options.


const queryObservable = af.database.list('/items', {
  query: {
    orderByChild: 'size',
    equalTo: 'large' 
  }
});

Creating a query with observable values

So here what we can do is instead of providing simple values like the previous example we can provide an observable and then query will automatically re-run when those values get changed.


const subject = new Subject(); // import {Subject} from 'rxjs/Subject';
const queryObservable = af.database.list('/items', {
  query: {
    orderByChild: 'size',
    equalTo: subject 
  }
});
// subscribe to changes
queryObservable.subscribe(queriedItems => {
  console.log(queriedItems);  
});
// trigger the query
subject.next('large');
// re-trigger the query!!!
subject.next('small');

And this is the full power of angularfire2, a really feature rich implementation of rxjs for using firebase, in the context of angular2.

Authentication

Another really important feature of Firebase and angularfire2 is authentication. Angularfire2 allows us to specify authentication methods in the bootstrap phase of the application (when we provided the default firebase configuration).

For example for google authentication :


bootstrap(<MyApp>Component, [
  FIREBASE_PROVIDERS,
  defaultFirebase({
    apiKey: "<your-key>",
    authDomain: "<your-project-authdomain>",
    databaseURL: "<your-database-URL>",
    storageBucket: "<your-storage-bucket>",
  }),
  firebaseAuthConfig({
    provider: AuthProviders.Google,
    method: AuthMethods.Redirect
  })
]);

This tells firebase and angular that we want to use the firebase google provider, and we will see how we can trigger it in our components.

Logging users in

If you have provided the method as in the previous example all you need to do is call af.auth.login. The exception would only be if you're using username and password, then you'd have to call af.auth.login() with the user's credentials.


af.auth.login({ email: 'email', password: 'pass' });

But you can also provide the configuration inside the login call, and in that case you don’t have to provide it in the bootstrap phase, although that’s the recommended way.


// Anonymous
af.auth.login({
  provider: AuthProviders.Anonymous,
  method: AuthMethods.Anonymous,
})

// Email and password
af.auth.login({
  provider: AuthProviders.Password,
  method: AuthMethods.Password,
})

// Social provider redirect
af.auth.login({
  provider: AuthProviders.Twitter,
  method: AuthMethods.Redirect,
})

// Social provider popup
af.auth.login({
  provider: AuthProviders.Github,
  method: AuthMethods.Popup,
})

Notes

So as you can see angularfire2 provides a really solid way of integrating Firebase and Angular2.

There are some issues to be resolved still but in general the library already works pretty well, if you are using some server side or electron with angular2 you might want to check this issue about how to start the app using a Service account

So go out, play with it give feedback, you will be surprised how easy it is to get started. If you are using cli, webpack or just plain system js the library is really easy to get going and playing with.