Quantcast
Channel: Devdactic – Ionic Tutorials
Viewing all articles
Browse latest Browse all 183

How to Build An Ionic App with Firebase and AngularFire 4

$
0
0

When it comes to building an Ionic app with a solid backend, the current choice for many people is Firebase. And for reasons.

The process of connecting an Angular app to Firebase is fairly easy in combination with the great AngularFire package, which is currently at the state of a release candidate for a new version 4. We will be using that version to build a simple cloud based shopping app with Ionic and Firebase!

Once we are done with the app our result inside the app and Firebase database might look like in the image below.
firebase-shopping-list

Setup the App

We start y creating a blank new Ionic app. With the new Ionic CLI 3 there are now changes for these commands so you should be fine to run:

ionic start devdacticShopping blank
cd devdacticShopping
npm install angularfire2@4.0.0-rc0 firebase --save
ionic g provider firebase

We only need the AngularFire package at the currently latest version and the official Firebase package. Besides the packages we generate a FirebaseProvider which will be our connection to Firebase within the app.

Now we also need to create our app inside Firebase, so go ahead and sign in or connect your Google account if you haven’t done already. Inside your Firebase console you have the option to create a new app, so do it now and select a region where you think your users will most likely live.

firebase-create-project

When you now go into your app you will see a view with 3 circles allowing you to add Firebase to your app. You can already copy most of the code from the “Add Firebase to your web app” overlay because we need it in the next step!

Configure our Firebase Connection

Now that we got the config for the connection we can jump right into our Ionic app and configure AngularFire. We use the copied config and paste it above our module insie src/app/app.module.ts.

We also import our new provider, and finally the different packages of AngularFire as those are now separate and not all in one!

Finally we call initializeApp() with the config for our app to easily establish the connection to Firebase.

Go ahead and change your module file to:

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 { HttpModule } from '@angular/http';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireModule } from 'angularfire2';
import { FirebaseProvider } from './../providers/firebase';

const firebaseConfig = {
    apiKey: "YOURKEY",
    authDomain: "domain.firebaseapp.com",
    databaseURL: "https://domain.firebaseio.com",
    projectId: "yourvalues",
    storageBucket: "dmaoin.appspot.com",
    messagingSenderId: "yourvalues"
  };

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

Before we dive into the rest of the code we need to change the Firebase security rules (for now). If you havenÄ’t heard of them, you can specify some JSON rules for your data nodes to prevent read or write access to different parts of your database.

In our case we are not using authentication here so we can disabled the rules. Navigate inside Firebase to Database -> Rules and change your rules to these dumb rules:

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

Now everyone can read and write the data, but for now that’s fine.

Create our Firebase Provider

Our Firebase Provider will handle all the exchange of data between our app and Firebase, or between our App and AngularFire in this case.

We need to import the database module from AngularFire and create 3 functions to either get a list of items, add an item or remove an item of our shopping list.

All of these operations can be easily performed by calling list() with the name of our node (we just say it will be “shoppingItems”) on our AngularFire database.

If we add push() a new node will be inserted with an automatically created id, and if we call remove() we can remove a node again by its id!

Now go ahead and change your src/providers/firebase/firebase.ts to:

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Injectable()
export class FirebaseProvider {

  constructor(public afd: AngularFireDatabase) { }

  getShoppingItems() {
    return this.afd.list('/shoppingItems/');
  }

  addItem(name) {
    this.afd.list('/shoppingItems/').push(name);
  }

  removeItem(id) {
    this.afd.list('/shoppingItems/').remove(id);
  }
}

Nothing really fancy, but this will help us in the next step inside our view.

I know many people would use AngularFire directly from the view, but I still like to keep these things separate from our actual class that controls the view. Let me know your opinion on this if you think different!

Loading & Displaying Data from Firebase

We can already load the data, but we can’t show it. So let’s change that!

Inside our HomePage we will assign the list of items to our array which has the type FirebaseListObservable, so we will always see any updates on this object if we use it correct.

Inside the view we will have a simple input field, so whenever addItem() is called we add the current value of our input to our shopping list bucket through our provider.

For remove we will pass the id of the object from our view to the function here and then delete it. Really, no magic in this class so open the src/pages/home/home.ts and insert:

import { FirebaseService } from './../../providers/firebase-service';
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FirebaseListObservable } from 'angularfire2/database';

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

  constructor(public navCtrl: NavController, public firebaseProvider: FirebaseProvider) {
    this.shoppingItems = this.firebaseProvider.getShoppingItems();
  }

  addItem() {
    this.firebaseProvider.addItem(this.newItem);
  }

  removeItem(id) {
    this.firebaseProvider.removeItem(id);
  }
}

To wrap everything up it would be good to see our result on the screen.. Therefore we build a list of items, and each of these items can be slide to the side to reveal the remove button.

Above the list we add our very simple input field so we can also capture and add new shopping items.

Add this to your src/pages/home/home.html:

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Shopping List
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-row>
    <ion-col col-9>
      <ion-item>
        <ion-input type="text" [(ngModel)]="newItem" placeholder="New Shopping item"></ion-input>
      </ion-item>
    </ion-col>
    <ion-col>
      <button ion-button (click)="addItem()">Add!</button>
    </ion-col>
  </ion-row>

  <ion-list>
    <ion-item-sliding *ngFor="let item of shoppingItems | async">
      <ion-item>
        {{ item.$value }}
      </ion-item>
      <ion-item-options side="right">
        <button ion-button color="danger" icon-only (click)="removeItem(item.$key)"><ion-icon name="trash"></ion-icon></button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>
</ion-content>

If you run your app now, you should be able to add, remove and most important see all updates inside the app and our Firebase database, just like in the image below!

firebase-shopping-list

Conclusion

Adding Firebase to your Ionic project is a matter of minutes, and establishing the connection through AngularFire is as easy as always with the latest update.

If you also want to use authentication, you also need to import another module from AngularFire but the use is as easy as the database!

You can find a video version of this article below, there we still use the old Ionic CLI but that only changes a few names.

Happy Coding,
Simon

The post How to Build An Ionic App with Firebase and AngularFire 4 appeared first on Devdactic.


Viewing all articles
Browse latest Browse all 183

Trending Articles