Let’s learn how to install and setup AngularFire2 4.0

F.Laurens
letsboot
Published in
4 min readJul 1, 2017
Sponsored by: letsboot.com

Check out our Angular In-House trainings or a public Angular courses.
Try out fossilo.com, our angular project to archive complete websites.

or our Web platform “letslearn” in order to manage Angular training courses, we have obviously chosen Angular4 and Firebase4 to build this new application!

In here, we will learn how to create a new project with angular/cli, Firebase Authentication for login and Firebase Database to read data.

New upgrades of AngularFire2 have been released at the end of May 2017 so AngularFire2 4.0 has been used for this project.

Create a new Firebase

Generate two Firebase databases: one for development (letslearn-dev) and one for production (letslearn).

2 ways to do it:

> add project in the Firebase console

> import an existing Google project from Google Cloud Platform

Start a new Angular project

Install angular-cli using npm.

npm install -g @angular/cli

Generate your new project, move into the repository and run your server.

ng new letslearn --prefix lsl
cd letslearn
ng serve -o

Your local application is now loaded in your browser: http://localhost:4200/ You can change the default port with the option — port. The message “Welcome to lsl!!” should be displayed!

Install and setup your Firebase

Install the latest version of AngularFire2 and Firebase with npm.

npm install angularfire2 firebase --save

Copy-paste your Firebase configuration from the Overview section and add it to your environment variable files:

> src/environments/environment.ts for development (letslearn-dev)

> src/environments/environment.prod.ts for production (letslearn)

export const environment = {
production: false,
firebase: {
apiKey: 'xxx',
authDomain: 'xxx.firebaseapp.com',
databaseURL: 'https://xxx.firebaseio.com',
projectId: 'xxx',
storageBucket: 'xxx.appspot.com',
messagingSenderId: 'xxx'
}
};

Setup and import AngularFire modules

Go to src/app/app.module.ts to setup and import the modules you need for your application.

Import AngularFireModule, AngularFireDatabaseModule and AngularFireAuthModule from angularfire2 and environment to get the Firebase setup.

import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { environment } from 'environments/environment';

Then add modules in NgModule. It is possible to customize your Firebase name using ‘initialiazeApp’.

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase, 'letslearn-dev'),
AngularFireDatabaseModule,
AngularFireAuthModule
],
bootstrap: [AppComponent]
})
export class AppModule { }

Create an AuthService to manage authentication.

You can create it in a shared folder.

ng generate service shared/auth

Then, import it into src/app/app.module.ts and register the AuthService in providers.

import { AuthService } from './shared/auth.service';@NgModule({
providers: [AuthService],
})

In src/app/shared/auth.service.ts, import AngularFireAuth from angularfire2, firebase from firebase and Observable. Inject AngularFireAuth and subscribe to get the current user into the service’s constructor.

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
export class AuthService {
private authState: Observable<firebase.User>
private currentUser: firebase.User = null;
constructor(public afAuth: AngularFireAuth) {
this.authState = this.afAuth.authState;
this.authState.subscribe(user => {
if (user) {
this.currentUser = user;
} else {
this.currentUser = null;
}
});
}
getAuthState() {
return this.authState;
}
}

Implement the authentication

Inject your Firebase Auth service in your app component.

import { AuthService } from './shared/auth.service';export class AppComponent implements OnInit {
user = null;
constructor(
private auth: AuthService) { }
ngOnInit() {
this.auth.getAuthState().subscribe(
(user) => this.user = user);
}
}

Add a login with a Google function

In your src/app/shared/auth.service.ts, add this function and enable the sign-in provider into the Firebase console > Authentication section >Sign-in method tab.

loginWithGoogle() {
return this.afAuth.auth.signInWithPopup(
new firebase.auth.GoogleAuthProvider());
}

In your src/app/app.component.ts

export class AppComponent implements OnInit {constructor(
private auth: AuthService) { }
loginWithGoogle() {
this.auth.loginWithGoogle();
}
}

Add AngularFireDatabase

Inject AngularFireDatabase in your component.

Open src/app/app.component.ts

Import AngularFireDatabase from angularfire2. Possibly, import also FirebaseListObservable and/or FirebaseObjectObservable if you need to bind to a list or an object.

import { Component, OnInit } from '@angular/core';
import { AuthService } from './shared/auth.service';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';

Inject the AngularFireDatabase into the component’s constructor.

constructor(
private auth: AuthService,
public db: AngularFireDatabase) { }

Then, set up your topics variable as a FirebaseListObservable and set your list of topics inside the ngOnInit function.

export class AppComponent implements OnInit {
topics: FirebaseListObservable<any[]>;
ngOnInit() {
this.auth.getAuthState().subscribe(
(user) => this.user = user);
this.topics = this.db.list('/topics');
}
}

You might get an error such as “Client doesn’t have permission to access the desired data” in your browser console when you run the server. You don’t have the good rules to read and/or write the data from/in the Firebase. To fix this, go to Firebase Console > Database section > Rules tab and change the rules!

Example of the rules in the Firebase console.

Edit your template

Open src/app/app.component.html

Add a button to login with Google and bind to login with your Google function.

<button (click)="loginWithGoogle()">Login with Google</button>

Display your list of topics using a For loop and do not forget the async pipe.

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

That’s it! Easy isn’t it? You can now create a new project with a Firebase database, use AngularFireAuth for authentication and AngularFireDatabase for reading data from your database. Implement it to your project and test different sign-in methods!

Now let’s code!

Next time we will do more with Firebase, Angular4 and data. Follow me on Medium.com or Twitter to get the next articles!

--

--

F.Laurens
letsboot

Database and software developer, biology lover, scuba and free diver