Sunteți pe pagina 1din 55

1.

Installation and Setup


Getting started with AngularFire2 is easy with the Angular CLI. Follow the 10 steps below
to get started. Don't worry, we're always working to make this shorter.

0. Prerequisites
Before you start installing AngularFire2, make sure you have latest version of angular-cli
installed. To verify run the command ng -v and ensure you see angular-cli: 1.x.x-
beta.xx. The lowest compatible version is 1.x.x-beta.14.
If not, you may need to do the following:

# if you have the wrong cli version only


npm uninstall -g angular-cli
npm uninstall -g @angular/cli
npm cache clean

# reinstall clean version


npm install -g @angular/cli@latest

You need the Angular CLI, typings, and TypeScript.

npm install -g @angular/cli@latest


# or install locally
npm install @angular/cli --save-dev
# make sure you have typings installed
npm install -g typings
npm install -g typescript

1. Create a new project


ng new <project-name>
cd <project-name>

The Angular CLI's new command will set up the latest Angular build in a new project
structure.

2. Test your Setup


ng serve
open http://localhost:4200

You should see a message that says App works!

3. Install AngularFire 2 and Firebase


npm install angularfire2 firebase --save

Now that you have a new project setup, install AngularFire2 and Firebase from npm.

4. Add Firebase config to environments variable


Open /src/environments/environment.ts and add your Firebase configuration:
export const environment = {
production: false,
firebase: {
apiKey: '<your-key>',
authDomain: '<your-project-authdomain>',
databaseURL: '<your-database-URL>',
projectId: '<your-project-id>',
storageBucket: '<your-storage-bucket>',
messagingSenderId: '<your-messaging-sender-id>'
}
};

5. Setup @NgModule for the AngularFireModule


Open /src/app/app.module.ts, inject the Firebase providers, and specify your Firebase
configuration. This can be found in your project at the Firebase Console:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';

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

Custom FirebaseApp Names

You can optionally provide a custom FirebaseApp name with initializeApp.


@NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase, 'my-app-name')
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}

6. Setup individual @NgModules


After adding the AngularFireModule you also need to add modules for the individual
@NgModules that your application needs.

AngularFireAuthModule
AngularFireDatabaseModule
AngularFireStorageModule (Future release)
AngularFireMessagingModule (Future release)

Adding the Firebase Database and Auth Modules

For example if you application was using both Firebase authentication and the Firebase
database you would add:

import { BrowserModule } from '@angular/platform-browser';


import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { environment } from '../environments/environment';

@NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase, 'my-app-name'), // imports
firebase/app needed for everything
AngularFireDatabaseModule, // imports firebase/database, only needed for database
features
AngularFireAuthModule, // imports firebase/auth, only needed for auth features
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}

7. Inject AngularFireDatabase
Open /src/app/app.component.ts, and make sure to modify/delete any tests to get the
sample working (tests are still important, you know):
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

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

}
}

8. Bind to a list
In /src/app/app.component.ts:
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

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

Open /src/app/app.component.html:
<ul>
<li class="text" *ngFor="let item of items | async">
{{item.$value}}
</li>
</ul>

9. Run your app


ng serve

Run the serve command and go to localhost:4200 in your browser.


And that's it! If it's totally borked, file an issue and let us know.

Next Step: Retrieving data as objects

Troubleshooting

1. Cannot find namespace 'firebase'.


If you run into this error while trying to invoke ng serve, open src/tsconfig.json and add
the "types" array as follows:
{
"compilerOptions": {
...
"typeRoots": [
"../node_modules/@types"
],

// ADD THIS
"types": [
"firebase"
]
}
}

2. Cannot find name 'require' (This is just a temporary workaround for the Angular
CLI).

If you run into this error while trying to invoke ng serve, open src/typings.d.ts and add
the following two entries as follows:
declare var require: any;
declare var module: any;
2. Retrieving data as objects
AngularFire2 synchronizes data as objects using the FirebaseObjectObservable.
The FirebaseObjectObservable is not created by itself, but through
the AngularFireDatabase service. The guide below demonstrates how to retrieve, save,
and remove data as objects.

Injecting the AngularFireDatabase service

Make sure you have bootstrapped your application for AngularFire2. See the
Installation guide for bootstrap setup.

AngularFireDatabase is a service which can be injected through the constructor of your


Angular component or @Injectable()service.
If you've followed the earlier step "Installation and Setup"
your /src/app/app.component.ts should look like below.
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
items: FirebaseListObservable<any[]>;
constructor(db: AngularFireDatabase) {
this.items = db.list('items');
}
}
In this section, we're going to modify the /src/app/app.component.ts to retreive data as
object.

Create an object binding

Data is retrieved through the af.database service.


There are two ways to create an object binding:

1. Relative URL
2. Absolute URL

// relative URL, uses the database url provided in bootstrap


const relative = db.object('/item');
// absolute URL
const absolute = db.object('https://<your-app>.firebaseio.com/item');

Retrieve data
To get the object in realtime, create an object binding as a property of your component
or service. Then in your template, you can use the async pipe to unwrap the binding.
Replace the FirebaseListObservable to FirebaseObjectObservable in
your /src/app/app.component.ts as below. Also notice the templateUrl changed to inline
template below:
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from
'angularfire2/database';

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

Saving data

API Summary
The table below highlights some of the common methods on
the FirebaseObjectObservable.
method

Replaces the current value in the database with the new value specified as the paramet
set(value: any) a destructive update, because it deletes everything currently in place and saves the ne

update(value: Updates the current value with in the database with the new value specified as the par
Object) a non-destructive update, because it only updates the values specified.

remove() Deletes all data present at that location. Same as calling set(null).
Returning promises

Each data operation method in the table above returns a promise. However, you should
rarely need to use the completion promise to indicate success, because the realtime
database keeps the object in sync.

The promise can be useful to chain multiple operations, catching possible errors from
security rules denials, or for debugging.

const promise = db.object('/item').remove();


promise
.then(_ => console.log('success'))
.catch(err => console.log(err, 'You dont have access!'));

Saving data
Use the set() method for destructive updates.
const itemObservable = db.object('/item');
itemObservable.set({ name: 'new name!'});

Updating data
Use the update() method for non-destructive updates.
const itemObservable = db.object('/item');
itemObservable.update({ age: newAge });
Only objects are allowed for updates, not primitives. This is because using an update
with a primitive is the exact same as doing a .set() with a primitive.

Deleting data
Use the remove() method to remove data at the object's location.
const itemObservable = db.object('/item');
itemObservable.remove();
Example app:

import { Component } from '@angular/core';


import { AngularFireDatabase, FirebaseObjectObservable } from
'angularfire2/database';

@Component({
selector: 'app-root',
template: `
<h1>{{ item | async | json }}</h1>
<input type="text" #newname placeholder="Name" />
<input type="text" #newsize placeholder="Size" />
<br />
<button (click)="save(newname.value)">Set Name</button>
<button (click)="update(newsize.value)">Update Size</button>
<button (click)="delete()">Delete</button>
`,
})
export class AppComponent {
item: FirebaseObjectObservable<any>;
constructor(db: AngularFireDatabase) {
this.item = db.object('/item');
}
save(newName: string) {
this.item.set({ name: newName });
}
update(newSize: string) {
this.item.update({ size: newSize });
}
delete() {
this.item.remove();
}
}

Meta-fields on the object

Data retrieved from the object binding contains special properties retrieved from the
unwrapped Firebase DataSnapshot.

property

$key The key for each record. This is equivalent to each record's path in our database as it would be re

If the data for this child node is a primitive (number, string, or boolean), then the record itself wil
$value
primitive value will be stored under $value and can be changed and saved like any other field.

Retrieving the snapshot

AngularFire2 unwraps the Firebase DataSnapshot by default, but you can get the data as
the original snapshot by specifying the preserveSnapshot option.
this.item = db.object('/item', { preserveSnapshot: true });
this.item.subscribe(snapshot => {
console.log(snapshot.key)
console.log(snapshot.val())
});
Querying?

Because FirebaseObjectObservable synchronizes objects from the realtime database,


sorting will have no effect for queries that are not also limited by a range. For example,
when paginating you would provide a query with a sort and filter. Both the sort
operation and the filter operation affect which subset of the data is returned by the
query; however, because the resulting object is simply json, the sort order will not be
preseved locally. Hence, for operations that require sorting, you are probably looking for
a list
3. Retrieving data as lists
AngularFire2 synchronizes data as lists using the FirebaseListObservable.
The FirebaseListObservable is not created by itself, but through
the AngularFireDatabase service. The guide below demonstrates how to retrieve, save,
and remove data as lists.

Injecting the AngularFireDatabase service

Make sure you have bootstrapped your application for AngularFire2. See the
Installation guide for bootstrap setup.

AngularFireDatabase is a service which can be injected through the constructor of your


Angular component or @Injectable()service. In the previous step, we modified
the /src/app/app.component.ts to retrieve data as object. In this step, let's start with a
clean slate.
Replace your /src/app/app.component.ts from previous step to look like below.
import { Component } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

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

}
}
In this section, we're going to modify the /src/app/app.component.ts to retreive data as
list, but before that let's look at ways around how to bind to a list.

Create a list binding

Data is retrieved through the AngularFireDatabase service.


There are three ways to create a list binding:

1. Relative URL
2. Absolute URL
3. Query
// relative URL, uses the database url provided in bootstrap
const relative = db.list('/items');
// absolute URL
const absolute = db.list('https://<your-app>.firebaseio.com/items');
// query
const queryList = db.list('/items', {
query: {
limitToLast: 10,
orderByKey: true
}
});

Retrieve data
To get the list in realtime, create a list binding as a property of your component or
service. Then in your template, you can use the async pipe to unwrap the binding.
Update /src/app/app.component.ts to import FirebaseListObservable from angularfire2
and iterate thru the list once data is retrieved. Also note the change in
attribute templateUrl to inline template below.
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items | async">
{{ item | json }}
</li>
</ul>
`,
})
export class AppComponent {
items: FirebaseListObservable<any>;
constructor(db: AngularFireDatabase) {
this.items = db.list('/items');
}
}

Saving data

API Summary
The table below highlights some of the common methods on
the FirebaseListObservable.
method

push(value: any) Creates a new record on the list, using the Realtime Database's push-

update(keyRefOrSnap: string) Firebase

remove(key: string?) Deletes the item by key. If no parameter is provided, the entire list wil

Returning promises

Each data operation method in the table above returns a promise. However, you should
rarely need to use the completion promise to indicate success, because the realtime
database keeps the list in sync.

The promise can be useful to chain multiple operations, catching possible errors from
security rules denials, or for debugging.

const promise = db.list('/items').remove();


promise
.then(_ => console.log('success'))
.catch(err => console.log(err, 'You do not have access!'));

Adding new items


Use the push() method to add new items on the list.
const items = db.list('/items');
items.push({ name: newName });

Updating items in the list


Use the update() method to update existing items.
const items = db.list('/items');
// to get a key, check the Example app below
items.update('key-of-some-data', { size: newSize });

Removing items from the list


Use the remove() method to remove data at the list item's location.
const items = db.list('/items');
// to get a key, check the Example app below
items.remove('key-of-some-data');
Deleting the entire list

If you omit the key parameter from .remove() it deletes the entire list.
const items = db.list('/items');
items.remove();
Example app

import { Component } from '@angular/core';


import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from
'angularfire2/database';

@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items | async">
<input type="text" #updatetext [value]="item.text" />
<button (click)="updateItem(item.$key, updatetext.value)">Update</button>
<button (click)="deleteItem(item.$key)">Delete</button>
</li>
</ul>
<input type="text" #newitem />
<button (click)="addItem(newitem.value)">Add</button>
<button (click)="deleteEverything()">Delete All</button>
`,
})
export class AppComponent {
items: FirebaseListObservable<any>;
constructor(db: AngularFireDatabase) {
this.items = db.list('/messages');
}
addItem(newName: string) {
this.items.push({ text: newName });
}
updateItem(key: string, newText: string) {
this.items.update(key, { text: newText });
}
deleteItem(key: string) {
this.items.remove(key);
}
deleteEverything() {
this.items.remove();
}
}

Meta-fields on the object

Data retrieved from the object binding contains special properties retrieved from the
unwrapped Firebase DataSnapshot.
property

$key The key for each record. This is equivalent to each record's path in our database as it would be re

If the data for this child node is a primitive (number, string, or boolean), then the record itself wil
$value
primitive value will be stored under $value and can be changed and saved like any other field.

Retrieving the snapshot

AngularFire2 unwraps the Firebase DataSnapshot by default, but you can get the data as
the original snapshot by specifying the preserveSnapshot option.
this.items = db.list('/items', { preserveSnapshot: true });
this.items
.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.key)
console.log(snapshot.val())
});
})
4. Querying lists
Querying is a killer feature of AngularFire2. You can specify query values as observables,
and when those observables emit new values, the query is automatically re-run.

Creating a query with primitive/scalar values

Queries are created by specifying a query object on the FirebaseListObservable options.


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

method purpose

orderByChild Specify a child to order by.

orderByKey Boolean to order by Firebase Database keys.

orderByPriority Boolean to order by Firebase Database priority.

orderByValue Specify a value to order by.

equalTo 1 Limit list to items that contain certain value.

limitToFirst Sets the maximum number of items to return from the beginning of the ordered list of r

limitToLast Sets the maximum number of items to return from the end of the ordered list of results.

startAt 1 Return items greater than or equal to the specified key or value, depending on the order

endAt 1 Return items less than or equal to the specified key or value, depending on the order-by

1The Firebase SDK supports an optional key parameter for startAt, endAt,
and equalTo when ordering by child, value, or priority. You can specify the key parameter
using an object literal that contains the value and the key. For example: startAt: {
value: 'some-value', key: 'some-key' }.

Invalid query combinations

Queries can only be ordered by one method. This means you can only
specify orderByChild, orderByKey, orderByPriority, or orderByValue.
// WARNING: Do not copy and paste. This will not work!
const queryObservable = db.list('/items', {
query: {
orderByChild: 'size',
equalTo: 'large',
orderByKey: true,
}
});
You can only use limitToFirst or limitToLast, but not both in combination.
// WARNING: Do not copy and paste. This will not work!
const queryObservable = db.list('/items', {
query: {
limitToFirst: 10,
limitToLast: 100,
}
});

Creating a query with observable values

Rather than specifying regular values, observables can be used to dynamically re-run
queries when the observable emits a new value.

This is the magic of AngularFire2.

An RxJS Subject is imported below. A Subject is like an Observable, but can multicast to
many Observers. Subjects are like EventEmitters: they maintain a registry of many
listeners. See, What is a Subject for more information.

const subject = new Subject(); // import {Subject} from 'rxjs/Subject';


const queryObservable = db.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');
Example app:

import { Component } from '@angular/core';


import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from
'angularfire2/database';
import { Subject } from 'rxjs/Subject';

@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items | async">
{{ item.text }}
</li>
</ul>
<div>
<h4>Filter by size</h4>
<button (click)="filterBy('small')">Small</button>
<button (click)="filterBy('medium')">Medium</button>
<button (click)="filterBy('large')">Large</button>
</div>
`,
})
export class AppComponent {
items: FirebaseListObservable<any[]>;
sizeSubject: Subject<any>;

constructor(db: AngularFireDatabase) {
this.sizeSubject = new Subject();
this.items = db.list('/items', {
query: {
orderByChild: 'size',
equalTo: this.sizeSubject
}
});
}
filterBy(size: string) {
this.sizeSubject.next(size);
}
}
+To run the above example as is, you need to have sample data in you firebase
database with the following structure:"

-|items
-|item1
-|size: small
-|text: sample small text
-|item2
-|size: medium
-|text: sample medium text
-|item3
-|size: large
-|text: sample large text
5. User authentication
AngularFireAuth.authState provides you an Observable<firebase.User> to monitor your
application's authentication State.
AngularFireAuth.auth returns an initialized firebase.auth.Auth instance, allowing you to
log users in, out, etc. See the Firebase docs for more information on what methods are
availabile.
Example app:

import { Component } from '@angular/core';


import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Component({
selector: 'app-root',
template: `
<div> {{ (user | async)?.uid }} </div>
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
`,
})
export class AppComponent {

user: Observable<firebase.User>;

constructor(public afAuth: AngularFireAuth) {


this.user = afAuth.authState;
}

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

logout() {
this.afAuth.auth.signOut();
}
}

Cordova

Learn how to setup Firebase Authentication with Cordova in the Firebase Guides.
Using AngularFire2 with Ionic 2
This document provides you a walkthrough of integrating AngularFire2 Authentication
with Ionic2. The below setup has been tested on Windows 10, but it should be same for
Mac/Linux.

Ensure that you're executing these commands as Administrator on Windows


and sudo on Mac/Linux to avoid any errors.

Prerequisites
The first step is to ensure you've latest version of Node installed. You can get the latest
version from here. This will install both node and npm.

After installing node, check the version by executing the following command in your
prompt window.

C:\projects>node -v
v6.9.1
As of writting this document, this is the most stable version. If you're not on this version,
please upgrade yourself to latest version by installing node from here.

Check your npm version by executing the following command.

C:\projects>npm -v
3.10.8
Your Application code sits on top of Ionic Framework and the Ionic Framework sits
on top of Cordova.

Let's get them installed globally, so that all projects can use them.

Execute the following commands.

C:\projects>npm install -g cordova

C:\projects>npm install -g ionic


Once the above commands are executed successfully, Check the versions of corodva
and ionic by executing the following commands.

C:\projects>cordova -v
6.4.0

C:\projects>ionic -v
2.1.8
These are the latest versions as of writting this document.

On successful execution of above commands, you're all set to create your Ionic 2 app.
To create your app, change into the directory where you want your app to reside and
execute the following command

C:\projects> ionic start Ionic_AngularFire2_Project blank --v2


The command ionic start will create the project with name "Ionic_AngularFire2_Project"
using "blank" template.
The --v2 flag ensures, this is a Ionic2 project.
Change to the project directory, which was just created with above command

C:\projects\Ionic_AngularFire2_Project>
To start your app, execute the following command

C:\projects\Ionic_AngularFire2_Project> ionic serve


If everything is installed correctly, the app should open your browser with the dev server
running at following urlhttp://localhost:8100 and will display default home page.
Stop you server by pressing "ctrl + c", if it is still running from the above step and install
typings and typescript globally by executing the following commands:

Note:- typings is not required for our current application to work, but it will be helpful
incase you want to bring in external libraries and extend this application.

C:\projects\Ionic_AngularFire2_Project>npm install -g typings

C:\projects\Ionic_AngularFire2_Project>npm install -g typescript


Check typings and typescript versions by executing following commands:

C:\projects\Ionic_AngularFire2_Project>typings -v
2.0.0

C:\projects\Ionic_AngularFire2_Project>tsc -v
Version 2.0.10

Configuring AngularFire2 and Firebase


Install angularfire2 and firebase by executing the following command in your project
directory

C:\projects\Ionic_AngularFire2_Project>npm install angularfire2 firebase --save


This should add angularfire2 and firebase entry in your project's package.json file in
dependencies section. Something similar

"angularfire2": "^2.0.0-beta.6",
"firebase": "^3.6.1",

Setup @NgModule
Open your project in your favourite editor and open the app.module.ts file,
under src/app and add the following three entries.

1. Import AngularFireModule at top.

2. Define your firebaseConfig constant.

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

your app.module.ts file should look something like this.


import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

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>'
};

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

Inject AngularFireDatabase and Bind it to List


Now inject AngularFireDatabase in your component. Open your home.ts by going
into src/pages/home/home.ts and make the following changes:

1. Import "AngularFireDatabase, FirebaseListObservable" at the top of your component.

2. Inject your AngularFireDatabase dependency in the constructor.

3. Call the list method on the AngularFireDatabase service.

Your home.ts file should look like this.


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

items: FirebaseListObservable<any[]>;

constructor(public navCtrl: NavController, db: AngularFireDatabase) {


this.items = db.list('/items');
}

}
Update your home.html at src/pages/home/home.html, with following entry
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
<ion-item class="text" *ngFor="let item of items | async">
{{item.$value}}
</ion-item>
</ion-list>
</ion-content>
** Run your app by executing the following command **

C:\projects\Ionic_AngularFire2_Project> ionic serve


This should fetch the data from firebase.
Configuring AngularFire2 Auth with Ionic2

Continuing with the above example stop your server by pressing ctrl+c and go to
command prompt and generate a service by executing the following command
C:\projects\Ionic_AngularFire2_Project> ionic g provider AuthService
This should create the AuthService under src/providers/auth-service.ts. Update the
service with the following code.
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
// Do not import from 'firebase' as you'll lose the tree shaking benefits
import * as firebase from 'firebase/app';

@Injectable()
export class AuthService {
private authState: Observable<firebase.User>;
private currentUser: firebase.User;

constructor(public afAuth: AngularFireAuth) {


this.authState = afAuth.authState;
afAuth.subscribe((user: firebase.User) => {
this.currentUser = user;
});
}

get authenticated(): boolean {


return this.currentUser !== null;
}

signInWithFacebook(): firebase.Promise<FirebaseAuthState> {
return this.afAuth.auth.signInWithPopup(new
firebase.auth.FacebookAuthProvider());
}

signOut(): void {
this.afAuth.signOut();
}

displayName(): string {
if (this.currentUser !== null) {
return this.currentUser.facebook.displayName;
} else {
return '';
}
}
}
Add your service in app.module.ts. Your app.module.ts should look like this
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AngularFireModule } from 'angularfire2';
import { AuthService } from '../providers/auth-service';

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>'
};

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [AuthService]
})
export class AppModule { }
Update your home.html to add a login button. Your home.html should look like this
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
<ion-item class="text" *ngFor="let item of items | async">
{{item | json}}
</ion-item>
</ion-list>

<button ion-button outline (click)="signInWithFacebook()">Facebook</button>


</ion-content>
and finally, add the corresponding click handlers in home.ts as follows. Also, ensure
the AuthService is injected in the constructor. Your home.ts should look like this
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AuthService } from '../../providers/auth-service';


import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

items: FirebaseListObservable<any[]>;

constructor(public navCtrl: NavController, db: AngularFireDatabase, private _auth:


AuthService) {
this.items = db.list('/items');
}

signInWithFacebook(): void {
this._auth.signInWithFacebook()
.then(() => this.onSignInSuccess());
}

private onSignInSuccess(): void {


console.log("Facebook display name ",this._auth.displayName());
}

}
Now run your app and if everything is configured correctly, you should be able to click
on the login button in your app, which should open the facebook pop-up.

Once you authenticate yourself, you should see your Facebook display name in console.

You can try redirecting yourself to another page to grab additional details from
Facebook.

Running our application on mobile phone.

Ensure you've the platform added to your project. If not add the platform by executing
the following command.

C:\projects\Ionic_AngularFire2_Project>ionic platform add android

This adds android platform for your project. Replace android with ios, if you're on Mac
book or add both. The generic command is ionic platform add <platform-name>
Now, let's try to run the app in browser. Execute the command

C:\projects\Ionic_AngularFire2_Project> ionic run android

This should run the app on your mobile phone. Now click on the Facebook button and
you'll notice the button doesn't work anymore. This is because the code written so far is
good for running our application in browsers, but when running the application on
mobile phones, we need to have access to Native Mobile API's, which are provided
by Corodova Plugins.

We can access these corodva plugins, using Ionic Native, which are nothing but
wrappers for cordova plugins.

List of all Ionic Native API's for corodova plugins can be found here.

Let's look at configuring and installing facebook plugin here. Ensure you follow the steps
correctly to configure your app.

Once you create your app and make a note of your App ID, go to command prompt in
your project directory and execute the following command

C:\projects\Ionic_AngularFire2_Project>
ionic plugin add cordova-plugin-facebook4 --save --variable APP_ID="123456789" --
variable APP_NAME="myApp"

Replace App ID with your app id from portal and provide your app name.

This will install the corodva plugin for facebook.

Add the platform to your facebook portal as mentioned in the document here.

Now import the Platform and Facebook objects in your auth-service.ts


import { Platform } from 'ionic-angular';
import { Facebook } from 'ionic-native';
and update the signInWithFacebook() method.

your auth-service.ts code should look like this.


import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
// Do not import from 'firebase' as you'll lose the tree shaking benefits
import * as firebase from 'firebase/app';

import { Platform } from 'ionic-angular';


import { Facebook } from 'ionic-native';

@Injectable()
export class AuthService {
private authState: Observable<firebase.User>;
private currentUser: firebase.User;

constructor(public afAuth: AngularFireAuth) {


this.authState = afAuth.authState;
afAuth.subscribe((user: firebase.User) => {
this.currentUser = user;
});
}

get authenticated(): boolean {


return this.currentUser !== null;
}

signInWithFacebook(): firebase.Promise<FirebaseAuthState> {
if (this.platform.is('cordova')) {
return Facebook.login(['email', 'public_profile']).then(res => {
const facebookCredential =
firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
return this.afAuth.auth.signInWithCredential(facebookCredential);
});
} else {
return this.afAuth.auth.signInWithPopup(new
firebase.auth.FacebookAuthProvider());
}

signOut(): void {
this.afAuth.signOut();
}

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

Verfiy your app is running in browser by executing the following command

C:\projects\Ionic_AngularFire2_Project>ionic serve

Everything should work. Now trying running the app on your android phone

C:\projects\Ionic_AngularFire2_Project> ionic run android

Once the App launches click on the Facebook login button and it should open up the
native facebook app for authentication and once your enter credentials and gets
succesfully authenticated, it should redirect you back to the home page.
Using AngularFire2 with Ionic 3-Angular
4
This tutorial provides a walkthrough of integrating AngularFire2 Authentication with
Ionic3/Angular4. The below setup has been tested on Windows 10, but it should be
same for Mac/Linux.

Note: - If you're working with Ionic2 and Angular2.0, then you should refer to Auth-
with-Ionic2 tutorial here

Ensure that you're executing these commands as Administrator on Windows


and sudo on Mac/Linux to avoid any errors.

This tutorial uses Facebook as the sign-in provider. After completion of this tutorial, you
should be able to configure other sign-in providers like Twitter, Google on your own.

Prerequisites
The first step is to ensure you've latest version of Node installed. You can get the latest
version from here. This will install both node and npm.

After installing node, check the version by executing the following command in your
prompt window.

C:\projects>node -v
v6.10.2
As of writting this document, this is the most stable version. If you're not on this version,
please upgrade yourself to latest version by installing node from here.

Check your npm version by executing the following command.

C:\projects>npm -v
3.10.10
Install the Angular CLI, which will be used to build our Angular project and install
Angular version 4 later.

C:\projects>npm install -g @angular/cli


Check your angular version by executing the following command.

C:\projects>ng -v

@angular/cli: 1.0.0
node: 6.10.2
os: win32 x64
Your Application code sits on top of Ionic Framework and the Ionic Framework sits
on top of Cordova.

Let's get them installed globally, so that all projects can use them.

Execute the following commands.

C:\projects>npm install -g cordova

C:\projects>npm install -g ionic


Once the above commands are executed successfully, Check the versions of corodva
and ionic by executing the following commands.

C:\projects>cordova -v
6.4.0

C:\projects>ionic -v
2.2.3
These are the latest versions as of writting this document.

On successful execution of above commands, you're all set to create your app with Ionic
3 framework.

To create your app, change into the directory where you want your app to reside and
execute the following command

C:\projects> ionic start auth-ng4-ionic3-af2 blank --v2


The command ionic start will create the project with name "Ionic_AngularFire2_Project"
using "blank" template.
The --v2 flag ensures, this is a Ionic2 project.
Change to the project directory, which was just created with above command

C:\projects\auth-ng4-ionic3-af2>ionic info
Cordova CLI: 6.4.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.7
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.10.2
Xcode version: Not installed
You need to ensure you've got Ionic Framework Version 3, as shown above.

Alternatively you can open package.json to ensure you've got the following angualr and
Ionic versions
"dependencies": {
"@angular/common": "4.0.2",
"@angular/compiler": "4.0.2",
"@angular/compiler-cli": "4.0.2",
"@angular/core": "4.0.2",
"@angular/forms": "4.0.2",
"@angular/http": "4.0.2",
"@angular/platform-browser": "4.0.2",
"@angular/platform-browser-dynamic": "4.0.2",
"@ionic-native/core": "3.6.1",
"@ionic-native/splash-screen": "3.6.1",
"@ionic-native/status-bar": "3.6.1",
"@ionic/storage": "2.0.1",
"ionic-angular": "3.1.1",
"ionicons": "3.0.0",
"rxjs": "5.1.1",
"sw-toolbox": "3.4.0",
"zone.js": "^0.8.10"
},
"devDependencies": {
"@ionic/app-scripts": "1.3.7",
"typescript": "~2.2.1"
}
If not, replace them to match above. These are the latest as of writing this tutorial.

To start your app, execute the following command

C:\projects\auth-ng4-ionic3-af2> ionic serve


If everything is installed correctly, the app should open your browser with the dev server
running at following urlhttp://localhost:8100 and will display default home page.

Configuring AngularFire2 and Firebase


Install angularfire2 and firebase by executing the following command in your project
directory

C:\projects\auth-ng4-ionic3-af2>npm install angularfire2 firebase --save


This should add angularfire2 and firebase entry in your project's package.json file in
dependencies section. Something similar

"angularfire2": "^4.0.0-rc.0",
"firebase": "^3.9.0",

Setup @NgModule
Open your project in your favourite editor and open the app.module.ts file,
under src/app and add the following three entries.
1. Import AngularFireModule and AngularFireDatabaseModule at top.

2. Define your firebaseConfig constant.

3. Initialize your app, by adding AngularFireModule in the "imports" array in @NgModule

3. Also, add AngularFireDatabaseModule in the "imports" array in @NgModule

your app.module.ts file should look something like this.


import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';


import { HomePage } from '../pages/home/home';

import { AngularFireModule } from 'angularfire2';


import { AngularFireDatabaseModule } from 'angularfire2/database';

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>'
};

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
Inject AngularFire and Bind it to List
Now inject AngularFireDatabase in your component. Open your home.ts by going
into src/pages/home/home.ts and make the following changes:

1. Import "AngularFireDatabase, FirebaseListObservable" at the top of your component.

2. Inject your AngularFireDatabase dependency in the constructor.

3. Call the list method on AngularFireDatabase object.

Your home.ts file should look like this.


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
items: FirebaseListObservable<any[]>;

constructor(public navCtrl: NavController, afDB: AngularFireDatabase) {


this.items = afDB.list('/cuisines');
}

}
*Ensure you've items node in your database with some primitive data.
Update your home.html at src/pages/home/home.html, with following entry
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
<ion-item class="text" *ngFor="let item of items | async">
{{item.$value}}
</ion-item>
</ion-list>
</ion-content>
Run your app by executing the following command

C:\projects\auth-ng4-ionic3-af2> ionic serve


This should fetch the data from firebase.
Configuring Firebase/Facebook to talk to each other

Go to Facebook Developers Page here and create a new App.

Once the App is created, get the App ID and App Secret from the dashboard and come
back to Firebase Console.

1. Login to Firebase Console and click on the Authentication section on the left hand side
of the menu.
2. Click on Sign-In Method tab and click on Facebook under Sign-In Providers.
3. Paste the App ID and App Secret copied from Facebook dashboard here.
4. Next copy the "OAuth redirect URI" from Firebase console. We need to go back and add
it in Facebook dashboard.

This URI is important, since it tells facebook, where to redirect a user, once he is
successfully authenticated.

5. Click the Save button and come back to the facebook dashboard.

Go to your app in Facebook developers site ( Facebook Dashboard )

6. Ensure you see Facebook Login under products section, if not add it via the Add Product
Button.
7. Once you see Facebook Login under products, click on the button to go to settings and
there you should see "Valid OAuth redirect URIs" input field.
8. Enter the URI copied from Firebase Console and click on Save Changes.

That's it. This will ensure Facebook and Firebase are able to talk to each other.

As we were able to fetch data from Firebase database in the above step, let's focus
on authentication below, by removing calls to fetch data.
Let's add the following two buttons in our home.html
The home.html should look like below
<ion-header>
<ion-navbar>
<ion-title>
Auth with Ionic 3
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<button ion-button outline (click)="signInWithFacebook()">Login</button>
<button ion-button outline (click)="signOut()">Logout</button>
</ion-content>
Let's update the home.ts to add the corresponding methods:

1. First import AngularFireAuth from AngularFire2/auth.


2. Inject AngularFireAuth in the constructor
3. The AngularFireAuth has various signIn methods to which we can pass instance of
AuthProviders as shown below.

The home.ts should look like below


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFireAuth } from 'angularfire2/auth';


import * as firebase from 'firebase/app';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public navCtrl: NavController,


private afAuth: AngularFireAuth) { }

signInWithFacebook() {
this.afAuth.auth
.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then(res => console.log(res));
}

signOut() {
this.afAuth.auth.signOut();
}

}
Note the import of firebase from firebase/app, to take advantage of the tree-
shaking

Also, update your app.module.ts to contain following import


import { AngularFireAuthModule } from 'angularfire2/auth';
and add it to the imports array.

Run the app and click on the Login Button, you should see a pop-up asking you to enter
username and password for facebook to authenticate. Once authenticated, you should
see the response from Facebook in console window.

Inspect the Object in the console, under user property, you should see all the attributes
and we're going to use two of them, next.
Let's get the displayName from the user property, which we just saw on the console to be
rendered on the screen. The AngularFireAuth has an authState property, which returns an
observable, let's subcribe it to get notified everytime the Authentication state changes.
Add class property displayName and subscribe to the AngularFireAuth.authState property
in the constructor. Also add the property in our template to render them on screen.
Your home.ts should look as follows:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFireAuth } from 'angularfire2/auth';


import * as firebase from 'firebase/app';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

displayName;

constructor(public navCtrl: NavController,


private afAuth: AngularFireAuth) {
afAuth.authState.subscribe(user => {
if (!user) {
this.displayName = null;
return;
}
this.displayName = user.displayName;
});
}

signInWithFacebook() {
this.afAuth.auth
.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then(res => console.log(res));
}

signOut() {
this.afAuth.auth.signOut();
}

and home.html shouldlook like this


<ion-header>
<ion-navbar>
<ion-title>
Auth with Ionic 3
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>

<h1>Hello {{displayName}}</h1>

<button ion-button outline (click)="signInWithFacebook()">Login</button>


<button ion-button outline (click)="signOut()">Logout</button>
</ion-content>
Now run your app and if everything is configured correctly, you should be able to click
on the login button in your app, which should open the facebook pop-up.

Once you authenticate yourself, you should see your Facebook display name on your
screen. Click the Logout button, which will make the AuthState to null and you should
see the difference on your screen.

You can try redirecting yourself to another page to grab additional details from
Facebook and experiement on your own.

Running our application on mobile phone

Ensure you've the platform added to your project. If not add the platform by executing
the following command.

C:\projects\auth-ng4-ionic3-af2>ionic platform add android

This adds android platform for your project. Replace android with ios, if you're on Mac
book or add both. The generic command is ionic platform add <platform-name>
Now, let's try to run the app in browser. Execute the command

C:\projects\auth-ng4-ionic3-af2> ionic run android

This should run the app on your mobile phone. Now click on the Facebook button and
you'll notice the button doesn't work anymore. This is because the code written so far is
good for running our application in browsers, but when running the application on
mobile phones, we need to have access to Native Mobile API's, which are provided
by Corodova Plugins.

We can access these corodva plugins, using Ionic Native, which are nothing but
wrappers for cordova plugins.

List of all Ionic Native API's for corodova plugins can be found here.

Let's look at configuring and installing facebook plugin here. Ensure you follow the steps
correctly to configure your app.
Login to facebook dashboard here, go to your App and make a note of your App ID.
Next go to command prompt in your project directory and execute the following
command by replacing the APP_ID with your App Id and APP_NAME with your App Name.
C:\projects\auth-ng4-ionic3-af2>
ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable
APP_NAME="myApplication" --save
This should add following entry in your config.xml, located at the root of your project.

<plugin name="cordova-plugin-facebook4" spec="~1.7.4">


<variable name="APP_ID" value="1689092456387654" />
<variable name="APP_NAME" value="auth-ng4-ionic3-af2" />
</plugin>
This will install the corodva plugin for facebook.

You should also see a sub-folder named cordova-plugin-facebook4 under


your plugins folder.
Add the native dependencies by executing the following command.

C:\projects\auth-ng4-ionic3-af2>npm install --save @ionic-native/facebook


After executing the above command, ensure you got following entry in
your package.json
"@ionic-native/facebook": "^3.5.0",
Now import the Platform and Facebook objects in your home.ts and inject the objects in
constructor.
import { Platform } from 'ionic-angular';
import { Facebook } from '@ionic-native/facebook';
Update the "signInWithFacebook" method and use Platform Service to determine the
platform and run the appropriate code.

your home.ts should look as below


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFireAuth } from 'angularfire2/auth';


import * as firebase from 'firebase/app';

import { Platform } from 'ionic-angular';


import { Facebook } from '@ionic-native/facebook';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

displayName;

constructor(public navCtrl: NavController,


private afAuth: AngularFireAuth, private fb: Facebook, private platform:
Platform) {
afAuth.authState.subscribe((user: firebase.User) => {
if (!user) {
this.displayName = null;
return;
}
this.displayName = user.displayName;
});
}

signInWithFacebook() {
if (this.platform.is('cordova')) {
return this.fb.login(['email', 'public_profile']).then(res => {
const facebookCredential =
firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
return firebase.auth().signInWithCredential(facebookCredential);
})
}
else {
return this.afAuth.auth
.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then(res => console.log(res));
}
}

signOut() {
this.afAuth.auth.signOut();
}

You'll also need to add the "Facebook" object in the provider section in app.module.ts.

The final app.module.ts should look like below


import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';


import { HomePage } from '../pages/home/home';

import { AngularFireModule } from 'angularfire2';


import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { Facebook } from '@ionic-native/facebook';

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>'
};

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Facebook
]
})
export class AppModule {}

Verfiy your app is running in browser by executing the following command

C:\projects\auth-ng4-ionic3-af2>ionic serve
Everything should work. Now trying running the app on your android phone

C:\projects\auth-ng4-ionic3-af2> ionic run android


Once the App launches click on the Login button. You should get the facebook pop-up
window. Enter your credentials. On successful authentication, you should see your
Facebook Display name and profile picture on your screen.
Installing angular-cli on Windows 10
There had been installation issues of angular-cli on Windows 10 system. Most of the
time these errors are related to Python dependecies and node-gyp.
Something as below :

execSync@1.0.2 install C:\Users\User\AppData\Roaming\npm\node_modules\angu


lar-cli\node_modules\angular2-template-loader\node_modules\codecov\node_modules\
execSync
node install.js

[execsync v1.0.2] Attempting to compile native extensions.


{ [Error: spawn node-gyp ENOENT]
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn node-gyp',
path: 'node-gyp',
spawnargs: [ 'rebuild' ] }
[execSync v1.0.2]
Native code compile failed!!
Will try to use win32 extension.
npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing Set-Cookie h
ttps://nodesecurity.io/advisories/130
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher
to avoid a RegExp DoS issue
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher
to avoid a RegExp DoS issue

node-zopfli@2.0.1 install C:\Users\User\AppData\Roaming\npm\node_modules\a


ngular-cli\node_modules\compression-webpack-plugin\node_modules\node-zopfli
node-pre-gyp install --fallback-to-build
.......................
To resolve this issue, make sure you're upgraded to latest version of NPM and try
installing angular-cli. This seems to have worked on certain scenarios.

If the above doesn't works then the below steps should help. Please ensure all the
commands are executed as an Administrator.

Steps:

1) Install node-gyp from here


npm install -g node-gyp

2) Install Windows build tool from here


npm install --global windows-build-tools
*This will also install python

3) Install Angular-CLI
npm install -g angular-cli

This should install angular-cli without errors.

Post this installation, follow the installation guide to install AngularFire2 and
everything should work as expected.

Note:-
When you start your app using "ng serve" in the console, you might still see the below
errors. Despite these errors, the application should work as expected and should be able
to talk to Firebase.

ERROR in [default]
C:\angularFire2Test\node_modules\angularfire2\interfaces.d.ts:12:34
Cannot find namespace 'firebase'.

ERROR in [default] C:\angularFire2Test\src\typings.d.ts:6:12


Subsequent variable declarations must have the same type. Variable 'require' must be
of type 'NodeRequire',
but here has type 'any'.

ERROR in [default] C:\angularFire2Test\src\typings.d.ts:7:12


Subsequent variable declarations must have the same type. Variable 'module' must be
of type 'NodeModule',
but here has type 'any'.
Upgrading to AngularFire2 4.0
AngularFire2 4.0 is a refactor of the AngularFire2 package which implements
@NgModule, simplifies authentication, and better supports Angular 4.

Removing AngularFire for Modularity


Prior to 4.0, AngularFire2 did not take advantage of the Firebase SDK's modularity for
tree shaking. The AngularFire service has now been removed and the library broken up
into smaller @NgModules:

AngularFireModule
AngularFireDatabaseModule
AngularFireAuthModule

When upgrading, replace calls


to AngularFire.database and AngularFire.auth with AngularFireDatabase and AngularFireA
uth respectively.
constructor(af: AngularFire) {
af.database.list('foo');
af.auth;
}
Should now be:

constructor(db: AngularFireDatabase, afAuth: AngularFireAuth) {


db.list('foo');
afAuth.authState;
}

Simplified Authentication API


In 4.0 we've reduced the complexity of the auth module by providing
only firebase.User observers (AngularFireAuth.authState, AngularFireAuth.idToken) and
cutting the methods that were wrapping the Firebase SDK.
import { AngularFireAuth } from 'angularfire2/auth';
// Do not import from 'firebase' as you'd lose the tree shaking benefits
import * as firebase from 'firebase/app';
...

user: Observable<firebase.User>;
constructor(afAuth: AngularFireAuth) {
this.user = afAuth.authState; // only triggered on sign-in/out (for old behavior
use .idToken)
}
AngularFire2 exposes the raw Firebase Auth object via AngularFireAuth.auth. For actions
like login, logout, user creation, etc. you should use the methods available
to firebase.auth.Auth.
While convenient, the pre-configured login feature added unneeded
complexity. AngularFireModule.initializeApp no longer takes a default sign in method.
Sign in should be done with the Firebase SDK via firebase.auth.Auth:
login() {
this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
logout() {
this.afAuth.auth.signOut();
}

FirebaseListFactory and FirebaseObjectFactory API Changes


If you directly use FirebaseListFactory or FirebaseObjectFactory you will no longer be
able to pass in a string, it will instead expect a Firebase database reference.

Putting this all together

Here's an example of what AngularFire2 4.0 looks like:

import { NgModule, Component } from '@angular/core';


import { Observable } from 'rxjs/Observable';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable }
from 'angularfire2/database';
import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';
import { environment } from '../environments/environment';

// Do not import from 'firebase' as you'd lose the tree shaking benefits
import * as firebase from 'firebase/app';

@NgModule({
declarations: [ App ],
exports: [ App ],
imports: [
AngularFireModule.initializeApp(environment.firebase, 'my-app'),
AngularFireDatabaseModule,
AngularFireAuthModule
],
bootstrap[ App ]
})
export class MyModule { }

@Component({
selector: 'my-app',
template: `
<div> {{ (items | async)? | json }} </div>
<div> {{ (user | async)? | json }} </div>
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
`
})
export class App {
user: Observable<firebase.User>;
items: FirebaseListObservable<any[]>;
constructor(afAuth: AngularFireAuth, db: AngularFireDatabase) {
this.user = afAuth.authState;
this.items = db.list('items');
}
login() {
this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
logout() {
this.afAuth.auth.signOut();
}
}
#API Reference

Work in progress. See the developer guide for a comprehensive walkthrough of


AngularFire2.

AngularFire Service
The recommended way to take advantage of the AngularFire library is to use the
injectable AngularFire service.

import {Component} from '@angular/core';


import {bootstrap} from '@angular2/platform-browser';
import {Observable} from 'rxjs/Observable';
import {FIREBASE_PROVIDERS, defaultFirebase, AngularFire} from 'angularfire2';
import {Question} from './services/question';

@Component({
template:`
<ul>
<li *ngFor="let question of questions | async">
{{question.text}}
</li>
</ul>
`
})
class App {
questions:Observable<Question[]>
constructor(af:AngularFire) {
// Get an observable of a synchronized array from <firebase-root>/questions
this.questions = af.database.list('/questions');
}
}

bootstrap(App, [
// Common injectable providers from the AngularFire lib
FIREBASE_PROVIDERS,
// Tell AngularFire the base URL for the Firebase used throughout
defaultFirebase('https://<some-firebase>.firebaseio.com')
]);

FIREBASE_PROVIDERS
Contains all AngularFire provider configuration for Angular's dependency injection.

Type: any[]
Usage:

import {bootstrap} from '@angular/platform-browser';


import {App} from './app';
import {FIREBASE_PROVIDERS} from 'angularfire2';

bootstrap(App, FIREBASE_PROVIDERS);

defaultFirebase
Define the root url for the library, to resolve relative paths.

Type: string
Usage:

import {bootstrap} from '@angular/platform-browser';


import {FIREBASE_PROVIDERS, defaultFirebase} from 'angularfire2';

bootstrap(App, [
FIREBASE_PROVIDERS,
defaultFirebase('https://my.firebaseio.com')
]);

FirebaseRef
Injectable symbol to create a Firebase reference based on the url provided
by FirebaseUrl.
Type: Firebase
Usage:

import {Inject} from '@angular/core';


import {FirebaseRef} from 'angularfire2';
...
class MyComponent {
constructor(@Inject(FirebaseRef) ref:Firebase) {
ref.on('value', this.doSomething);
}
}

FirebaseUrl
URL for the app's default Firebase database.

Type: string
Usage:

import {bootstrap} from '@angular/platform-browser';


import {Inject} from '@angular/core';
import {FirebaseUrl, FIREBASE_PROVIDERS, defaultFirebase} from 'angularfire2';

@Component({
selector: 'app',
template: `<a [href]="url">{{ url }}</a>`
})
class App {
constructor(@Inject(FirebaseUrl) public url: string) {}
}

bootstrap(App, [
FIREBASE_PROVIDERS,
defaultFirebase('https://my.firebaseio.com')
]);

AngularFireAuth
Type: class
Injectable service for managing authentication state. Extends rxjs ReplaySubject, which
represents an object that is both an observable sequence as well as an observer.

Logging In

To log in a user, call the login method on an instance of FirebaseAuth class. The method
has the following two signatures:
login(config?: AuthConfiguration): firebase.Promise<FirebaseAuthState>;
login(credentials?: EmailPasswordCredentials |
firebase.auth.AuthCredential | string): firebase.Promise<FirebaseAuthState>;
login(credentials: EmailPasswordCredentials |
firebase.auth.AuthCredential | string, config?: AuthConfiguration):
firebase.Promise<FirebaseAuthState>
The signature that is used depends on which AuthMethod you chose to use to login.
AuthMethods.Popup, AuthMethods.Redirect, and AuthMethods.Anonymous all use the
first signature whereas AuthMethods.CustomToken, AuthMethods.OAuthToken, and
AuthMethods.Password use the second signature. This is because if you use these three
AuthMethods you need to provide a credentials argument to login.

AuthConfiguration

You MUST provide an AuthConfiguration object to use the login method, however you
do not need to pass it to login correctly. Instead you may choose to pass the
configuration in through DI. This helps keep your components modular because they
can simply call login and it will use whichever options were provided through DI. You
can use the firebaseAuthConfigMethod to generate a Provider object which you can pass
to DI like so:
import {bootstrap} from '@angular/core';
import {
FIREBASE_PROVIDERS,
defaultFirebase,
firebaseAuthConfig,
AuthProviders,
AuthMethods
} from 'angularfire2';
bootstrap(MyApp, [
FIREBASE_PROVIDERS,
defaultFirebase('https://<some-firebase>.firebaseio.com'),
firebaseAuthConfig({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup,
remember: 'default',
scope: ['email']
})
]);
Once you've done that you can simply call login on the auth object. This will
automatically use the options that were configured with DI. You can override those
options by providing an optional configuration object to the login method like so:
import {Component} from '@angular/core';
import {FirebaseAuth} from 'angularfire2';

@Component({
selector: 'my-component'
templateUrl: 'my_template.html'
})
export class MyApp {
constructor (private _auth: FirebaseAuth) {}

public doLogin () {
// This will perform popup auth with google oauth and the scope will be email
// Because those options were provided through bootstrap to DI, and we're
overriding the provider.
this._auth.login({
provider: AuthProviders.Google
});
}
}
The AuthConfiguration Object has the following signature

export interface AuthConfiguration {


method?: AuthMethods;
provider?: AuthProviders;
remember?: string;
scope?: string[];
}

The AuthMethods and AuthProviders are enums, defining values for Methods and
Providers respectively.
See Facebook-Login and Google-Signin for more information.

Usage:

....
signInWithFacebook(): Promise<FirebaseAuthState> {
return this.auth$.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup,
});
}
....
....
signInWithGoogle(): Promise<FirebaseAuthState> {
return this.auth$.login({
provider: AuthProviders.Google,
method: AuthMethods.Redirect,
});
....
login(credentials?: EmailPasswordCredentials | firebase.auth.AuthCredential |
string): firebase.Promise<FirebaseAuthState> :
Takes one of the three arguments as input. The EmailPasswordCredentials object is same,
as mentioned in createUser method. The login method can also take
a firebase.auth.AuthCredential object as mentioned here.
Usage:

....
signInWithEmail(): Promise<FirebaseAuthState> {
return this.auth$.login({
email: "yourName@gmail.com",
password: 'yourPassword'
});
....

Subscribing to Authentication State

Type: class FirebaseAuth extends ReplaySubject<FirebaseAuthState>


Usage:

import {FirebaseAuth} from 'angularfire2';


@Component({
selector: 'auth-status',
template: `
<div *ngIf="auth | async">You are logged in</div>
<div *ngIf="!(auth | async)">Please log in</div>
`
})
class App {
constructor (@Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
Alternatively, if you wish to extend an existing AngularFire component to monitor
authentication status:

import {AngularFire, FirebaseAuth} from 'angularfire2';


@Component({
selector: 'auth-status',
template: `
<div *ngIf="af.auth | async">You are logged in</div>
<div *ngIf="!(af.auth | async)">Please log in</div>
`
})
class App {
constructor(public af: AngularFire) {
this.af.auth.subscribe(auth => console.log(auth));
}
}
getAuth(): FirebaseAuthState : Returns the client's current Authentication State. The
FirebaseAuthState is an interface with following signature
export interface FirebaseAuthState {
uid: string;
provider: AuthProviders;
auth: firebase.User;
expires?: number;
github?: firebase.UserInfo;
google?: firebase.UserInfo;
twitter?: firebase.UserInfo;
facebook?: firebase.UserInfo;
anonymous?: boolean;
}
Sample Usage:

constructor(public auth: FirebaseAuth) {


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

get authenticated(): boolean {


return this.authState !== null;
}
logout(): Promise<void>:Deletes the authentication token issued by Firebase and signs
user out. See Auth.signOut() for more information.
Sample Usage:

signOut(): {
this.af.auth.logout().then(() => {
// user logged out
});
}
createUser(credentials: EmailPasswordCredentials):
firebase.Promise<FirebaseAuthState> : Creates a new user with email/password provided.
Returns a promise filled with FirebaseAuthState, which contains the uid of the created
user.
The credentials object is an object containing email and password of the user to be
created. See createUserWithEmailAndPassword for more information.
createNewUser(properties:Object): Promise<FirebaseAuthState> {
return this.auth.createUser({
email: 'uniqueName@gmail.com',
password: 'uniquePassword'
})
}

FirebaseListObservable
Subclass of rxjs Observable which also has methods for updating list-like Firebase data.
Type: class
Properties:

$ref:(firebase.database.Reference): The reference used to sync this collection to the


Firebase database. Seefirebase.database.Reference
Methods:

push:(val) => Promise: Add an element to the Firebase Database. This is the equivalent
of the Firebase SDK's
set() method. See Saving Data for info about restricted characters in object keys and
more details about saving data in the Database.
update:(item:Object) => void: Replace any child keys provided in val with the values
provided, but do not touch any other keys in the element. This is the equivalent of the
Firebase SDK's update() method.
remove:([item]) => void: Remove an element from the Firebase Database. If
no item argument is provided, it removes all elements from the list. This is the equivalent
of the Firebase SDK's remove() method.

FirebaseObjectObservable
Subclass of rxjs Observable which also has methods for syncing and updating object-like
Firebase data. {For collections and lists, see FirebaseListObservable.)
Type: class
Properties:

$ref:(firebase.database.Reference): The reference used to sync this collection to the


Firebase database. Seefirebase.database.Reference
Methods:

set:(val:any) => Promise:Replaces any data at this path in the Database with the value
provided here (or adds the data if it doesn't exist). This is the equivalent of the Firebase
SDK's
set() method. See Saving Data for info about restricted characters in object keys and
more details about saving data in the Database.
update:(val:Object) => void: Replace any child keys provided in val with the values
provided here. The primary difference between this method and set() above, is
that update() modifies only the keys provided, leaving any other data untouched,
where set() essentially replaces all data at the given path. This is the equivalent of the
Firebase SDK's update() method.
remove:() => void: Remove an element from the Firebase Database. If no item argument
is provided, it removes all elements from the list. This is the equivalent of the Firebase
SDK's remove() method.

S-ar putea să vă placă și