Angular

Angular 2 + Firebase Introduction


Introduction

Firebase is a mobile and web application platform supporting developers with various tools and services to build high-quality app. A central feature of Firebase is the realtime database. By using the Firebase API the realtime database can be used to store and snyc data across multiple clients and platforms. The Firebase website is available at: https://firebase.google.com/.

Firebase is a perfect match for Angular 2 application. The realtime database can be used as a backend for your web and mobile application. Together with the speed and performance Angular 2 delivers for the front-end the realtime data sync feature is able to further improve the user experience.

To integrate Firebase services with Angular 2 application The AngularFire2 library can be used. This is the official library for Firebase and Angular 2. In the following you’ll learn how to set up a Firebase realtime database and bind to realtime data in your Angular 2 application by using the AngularFire2 library step-by-step.

Setting Up Firebase

To set up Firebase you first need to go to https://firebase.google.com/ create an account and login to the Firebase console. The Firebase console gives you access to all firebase services and configuration options. First, we need to create a new Firebase project:
01Once created a project you can click on the project tile and you’ll be redirected to the Firebase project console:
02The project console is the central place for the Firebase configuration settings. From the menu on the left side you can access the various Firebase services. Click on the link Database to access the realtime database view:
03By default the Data tab is opened. Here you can see the URL of the realtime data and the content. You can use the online editor to add content to the database:
04As you can see the data in the realtime database is organized in a hierarchical tree which contains nodes and key-value-pairs. This is similar to a JSON data structure. Under the root node add a sub node items. Under items create a few key-value-pairs like you can see it in the screenshot. We’ll use these data elements in our sample application later on.

Finally, we need to edit the security rules of the database, so that we’re able to access data without authentication later on in our Angular 2 sample application. Switch to the tab Rules and edit the given security rules to correspond to the following:

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

Now read and write database access is possible without authentication.

Project Setup with Angular 2 CLI

Now, that the Firebase database is available, the next step is to initiate the Angular 2 sample application. We do that by using the Angular 2 CLI. If you haven’t installed the command line interface yet, you first need to execute the following command to make the ng command available on your system:

$ npm install -g angular-cli

Once the Angular 2 CLI is available we’re able to initiate a new Angular 2 project by executing the following command

$ ng new angular2fb

This creates the project folder angular2fb and inside this folder you’ll find the following initial project structure:

.
├── README.md
├── angular-cli.json
├── e2e
├── karma.conf.js
├── node_modules
├── package.json
├── protractor.conf.js
├── src
└── tslint.json

The subfolder src is containing the main implementation parts:

.
├── app
│ ├── app-routing.module.ts
│ ├── app.component.css
│ ├── app.component.html
│ ├── app.component.spec.ts
│ ├── app.component.ts
│ ├── app.module.ts
│ ├── index.ts
│ └── shared
│ └── index.ts
├── assets
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── index.html
├── main.ts
├── polyfills.ts
├── styles.css
├── test.ts
├── tsconfig.json
└── typings.d.ts

To check that the project has been initiated correctly you can now start up the web server by using the ng command in the following way:

$ ng serve

The application should then be accessible at http://localhost:4200 in your browser.

Installing Firebare and AngularFire 2

Now we need to add the Firebase and the AngularFire 2 library as dependencies to our project:

$ npm install angularfire2 firebase --save

By using the --save flag both dependencies are automatically added to the project’s package.json file.

Preparing Your Application for Firebase

Firebase Configuration

The Firebase configuration consists for four key-value pairs. The following information needs to be provided:

  • apiKey
  • authDomain
  • databaseURL
  • storageBucket

The easiest way to get all four pieces of configuration information is to go to the Firebase console, open the project view and use the Link Add Firebase to your web app. From the pop up which is opened you can copy a code snipped containing the configuration settings for your specific Firebase project.

Take the settings and paste it into a new file environments/firebase.config.ts in the following form:

export const firebaseConfig = {
  apiKey: '<your-key>',
  authDomain: '<your-project-authdomain>',
  databaseURL: '<your-database-URL>',
  storageBucket: '<your-storage-bucket>'
};

Also add the following two lines of code at the bottom of your typings.d.ts file in the root folder of the Angular 2 project:

declare var require: any;
declare var module: any;

and add the types property to the compilerOptions configuration object in tsconfig.json.

{
  "compilerOptions": {
    [...],
    "types": [
      "firebase"
    ]
  }
}

Importing AngularFireModule

To make use of the Angular Fire 2 library we need to import AngularFireModule first. Add the following import statement to your app.module.ts:

import { AngularFireModule } from 'angularfire2';

Use the module factory method initializeApp from AngularFireModule to create a Angular Fire 2 module which is based on our specific Firebase configuration:

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(firebaseConfig)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})export class AppModule {}

Inject AngularFire in Your Component

The AngularFire service is part of the AngularFireModule and now can be injected into your components. Switch to app.component.ts and add the following import statement first:

import { AngularFire, FirebaseListObservable } from 'angularfire2';

Second, inject AngularFire into that component:

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  constructor(af: AngularFire) {
  }
}

Use AngularFire to Get Access To Firebase Data – Bind To A Firebase List

With the AngularFire service injected in our component we can now access Firebase data by using that service. First we need to declare an object of type FirebaseListObservable<any[]>. With this observable we’re able to bind to a Firebase list and receive an array of data, like you can see in the following example:

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

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  items: FirebaseListObservable<any[]>;
  constructor(af: AngularFire) {
    this.items = af.database.list('/items');
  }
}

To bind to a list we’re using the database.list() method from the AngularFire service. We need to pass the name of the list endpoint as a string to the method call. By using the string ‚/items‘ we’re binding to the items list. The resulting FirebaseListObservable<any[]> object is stored in the items variable which is of the same type.

To print out the data received through the observable we can use the following template code:

<ul>
  <li class="text" *ngFor="let item of items | async">
    {{item.$value}}
  </li>
</ul>

Here we’re using the async pipe to subscribe to the Observable which is available in items. Using this pipe ensured that we’re getting the latest value which has been emitted. The result can be seen in the following:

05

To experience the realtime behavior of the database you can now go back to the Firebase console, open the Database view and add another data element:

06The output of our sample application is updated immediately without the need to reload the page:

07

ONLINE COURSE: Angular - The Complete Guide

Check out the great Angular – The Complete Guide with thousands of students already enrolled:

Angular – The Complete Guide

  • This course covers Angular 4
  • Develop modern, complex, responsive and scalable web applications with Angular
  • Use their gained, deep understanding of the Angular 2 fundamentals to quickly establish themselves as frontend developers
  • Fully understand the architecture behind an Angular 2 application and how to use it
  • Create single-page applications with on of the most modern JavaScript frameworks out there

Go To Course


Using and writing about best practices and latest technologies in web design & development is my passion.

    View Comments

    *