in

Setting Up Firebase with Angular 2 (ADVANCED)

In the previous tutorial, I mentioned how to setup Angular 2 with Firebase as your real-time database.

That method is limited and you’re using a bit of Javascript to maintain the database connection.  There’s a better way using angularfirebase2 instead of the basic firebase module.

You’ll need a Firebase account and project set up.  If you don’t have one, check out the previous tutorial on how to do that.

Installing Angular Fire 2

Install the angularfire2 module: npm install angularfire2 –save (within your project folder)

If you get errors about Duplicate Identifiers, it’s because you have installed both the firebase and angularfire2 modules… you only need one or the other.  If you got that, you can follow the instructions on github to resolve it.

Configuration File

In the Environments folder, create a file called firebase.config.ts

Add the following:

import {AuthMethods, AuthProviders} from "angularfire2";

export const firebaseConfig = {
    apiKey: [YOUR DATA],
    authDomain: [YOUR DATA],
    databaseURL: [YOUR DATA],
    storageBucket: [YOUR DATA],
    messagingSenderId: [YOUR DATA]
};


export const authConfig = {
    provider: AuthProviders.Password,
    method: AuthMethods.Password
};

Update App Module

Edit the app.module.ts file in the src/app folder.

Add this import to the file:

import {firebaseConfig} from "../environments/firebase.config";
import {AngularFireModule} from "angularfire2/index";

In the imports: section, add this line after BrowserModule:

AngularFireModule.initializeApp(firebaseConfig),

Update App Components

Editing the app.component.ts file in the src/app folder, add an import for AngularFire, like so:

import {AngularFire, FirebaseListObservable} from "angularfire2";

Then under the component annotation, add:

export class AppComponent {
  title = 'app works!';
  constructor(private af: AngularFire){

    const courses$ : FirebaseListObservable<any> = af.database.list('');
    courses$.subscribe(console.log);
  }
}

Testing the Connection

Seed your database with some sample data, and start your app.  In a browser load the page and view the console.  You should get the data returned into the console.

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Comments

Leave a Reply

Loading…

Setting Up Angular 2 with Firebase (EASY)

Angular2 Best Practices – Using Services