Ionic 2, AngularFire 2 and Firebase 3

  1. Create a new Ionic 2 project:
    ionic start example-ionic blank --v2
  2. Install Firebase 3 and AngularFire 2
    cd example-ionic
    npm install angularfire2 firebase —save
    typings install file:node_modules/angularfire2/firebase3.d.ts --save --global
  3. In app.ts
    import {Component} from '@angular/core';
    import {Platform, ionicBootstrap} from 'ionic-angular';
    import {StatusBar} from 'ionic-native';
    import {HomePage} from './pages/home/home';
    
    import {
     defaultFirebase,
     FIREBASE_PROVIDERS
    } from 'angularfire2';
    
    const COMMON_CONFIG = {
     apiKey: "YOUR_API_KEY",
     authDomain: "YOUR_FIREBASE.firebaseapp.com",
     databaseURL: "https://YOUR_FIREBASE.firebaseio.com",
     storageBucket: "YOUR_FIREBASE.appspot.com"
    };
    
    @Component({
     template: '<ion-nav [root]="rootPage"></ion-nav>',
     providers: [
     FIREBASE_PROVIDERS,
     defaultFirebase(COMMON_CONFIG)
     ]
    })
    export class MyApp {
     rootPage: any = HomePage;
    
     constructor(platform: Platform) {
     platform.ready().then(() => {
     // Okay, so the platform is ready and our plugins are available.
     // Here you can do any higher level native things you might need.
     StatusBar.styleDefault();
     });
     }
    }
    
    ionicBootstrap(MyApp);
  4. In home.ts
    import {Component} from '@angular/core';
    import {NavController} from 'ionic-angular';
    
    import {
     AngularFire,
     FirebaseObjectObservable
    } from 'angularfire2';
    
    @Component({
     templateUrl: 'build/pages/home/home.html'
    })
    export class HomePage {
     item: FirebaseObjectObservable<any>;
    
     constructor(private navCtrl: NavController, af: AngularFire) {
     this.item = af.database.object('/item');
     }
    }
  5. In home.html
    <ion-header>
     <ion-navbar>
     <ion-title>
     Ionic Blank
     </ion-title>
     </ion-navbar>
    </ion-header>
    
    <ion-content padding>
     The world is your oyster.
     <p>
     {{ (item | async)?.name }}
     </p>
    </ion-content>
  6. In your firebase console, make sure have an object under /item with a “name” property. This is what we load in our example code above.
  7. Test by running the app.
    ionic serve
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s