Ionic 2 Firebase CRUD Example - Part 1

by Didin J. on Dec 16, 2016 Ionic 2 Firebase CRUD Example - Part 1

A comprehensive step by step tutorial on Ionic 2 Firebase create-read-update-delete (CRUD) simple example first part.

Ionic 2 Firebase is the great combination for mobile apps development. Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users. Ionic 2 as mobile apps and Firebase as data storage, it's all connected using AngularFire. AngularFire is an officially supported Angular binding for Firebase which is a cloud database designed to power real-time, collaborative applications. So you don't need servers to build your Angular app. If not confidence how to started to create Ionic2 App you can jump back to previous tutorials or you just can skip and move forward with this tutorial.

Table of Contents:

Setup Google Firebase

Go to https://console.firebase.google.com and log in using your google account.

Ionic 2 Firebase CRUD - Firebase Console

Click CREATE NEW PROJECT button, name it as you like (mine: MyIonic2Project) and choose your country. Finally, click CREATE PROJECT button.

Ionic 2 Firebase CRUD - Firebase Console Overview

Click Settings (Gear Button) on the top left side of Overview then choose Project Settings. You will find api key in here. Go to database menu and click the RULES tab then edit to make your database writable and readable for everyone.

{
  "rules": {
    ".read": "auth == null",
    ".write": "auth == null"
  }
}

 

Create a New Ionic 2 Project

Now, create a new Ionic project using this command:

ionic start MyIonic2Firebase --v2

This might be a long time, just wait for it because it’s running npm install too. After finished you will get a default tabs app because we are not specified the template when we start a project, just leave it as tabs.

 

Configure Google Firebase and AngularFire2

Go to your Ionic project folder.

cd MyIonic2Firebase

Then install the required dependencies:

npm install @types/jasmine@^2.5.36 firebase angularfire2 --save

Open src/app/app.module.ts using your favorite IDE or text editor. Initialize or register firebase config in here. First, import firebase and angularfire2 dependencies after.

import { FIREBASE_PROVIDERS, defaultFirebase, AngularFire, AuthMethods, AuthProviders, firebaseAuthConfig } from 'angularfire2';

In provider declare FIREBASE_PROVIDERS.

providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},

    FIREBASE_PROVIDERS,

    defaultFirebase({

      apiKey: "",

      authDomain: "",

      databaseURL: "",

      storageBucket: "",

    })

  ]

Fill that configuration by a jump into your browser and firebase console. Look for api key that previously shown in Settings. AuthDomain in Authentication at side menu but first create sign-in method, for this example set anonymous to make everyone able to access it.  DatabaseUrl in the database menu. StorageBucket in Storage menu.

 

Build Ionic Firebase CRUD

For CRUD functions we are using default contact tabs which will be a contact list. Contact list gets data from firebase named contact and has structure name, address, city, and phone. We will modify the current contact page to meet new contact list structure and we add a page for add new contact form. 

First, we add the new page for additional contact using this ionic 2 command:

ionic g page addContact 

Let me explain a little about page generation command. “g” stands for generating, the page is which will be generated and addContact is the name of the page that will be generated. Name of the generated page using camel-case which will be add-contact in lowercase for both folder and file name.

Register this new add-contact page to app/app.module.ts, so it looks like this:

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

import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';

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

import { FIREBASE_PROVIDERS, defaultFirebase } from 'angularfire2';

import { AboutPage } from '../pages/about/about';

import { ContactPage } from '../pages/contact/contact';

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

import { TabsPage } from '../pages/tabs/tabs';

import { AddContactPage } from '../pages/add-contact/add-contact';



@NgModule({

  declarations: [

    MyApp,

    AboutPage,

    ContactPage,

    HomePage,

    TabsPage,

    AddContactPage

  ],

  imports: [

    IonicModule.forRoot(MyApp)

  ],

  bootstrap: [IonicApp],

  entryComponents: [

    MyApp,

    AboutPage,

    ContactPage,

    HomePage,

    TabsPage,

    AddContactPage

  ],

  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},

    FIREBASE_PROVIDERS,

    defaultFirebase({

      apiKey: "AIzaSyCrZpORU_czh2oUrAkRrN7TyuZChUNx0B4",

      authDomain: "myionic2firebase.firebaseapp.com",

      databaseURL: "https://myionic2firebase.firebaseio.com",

      storageBucket: "myionic2firebase.appspot.com",

    })

  ]

})

export class AppModule {}

Edit pages/contact/contact.ts and add a reference to add-contact page around other import lines.

import { AddContactPage } from '../add-contact/add-contact';

Create FirebaseListObservable contactList and populate with data fro Firebase. Also, add function for navigate to addContactPage.

export class ContactPage {

  contactList: FirebaseListObservable<any>;

  constructor(public navCtrl: NavController, public af: AngularFire) {

    this.contactList = af.database.list('/contacts');

  }


  addContact(){

    this.navCtrl.push(AddContactPage);

  }

}

Edit pages/contact/contact.html to add contact list and add-contact button.

<ion-header>

  <ion-navbar>
    <ion-title>
      Contact
    </ion-title>
    <ion-buttons end>
      <button (click)="addContact()">
        <ion-icon name="add"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-list-header>My Contacts</ion-list-header>
    <ion-item *ngFor="let contact of contactList | async">
      <ion-icon name="book" danger item-left></ion-icon>
      <h2>{{contact.name}}</h2>
      <h3>Address: {{contact.address}}, {{contact.city}}</h3>
      <p>Phone: {{contact.phone}}</p>
    </ion-item>
  </ion-list>
</ion-content>

Then, edit pages/add-contact/add-contact.ts. Import required angularFire, declare contactList and add function for adding a new contact.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AngularFire, FirebaseListObservable } from 'angularfire2';


@Component({
  selector: 'page-add-contact',
  templateUrl: 'add-contact.html'
})

export class AddContactPage {
  contactList: FirebaseListObservable<any>;
  constructor(public navCtrl: NavController, public af: AngularFire) {
    this.contactList = af.database.list('/contacts');
  }

  addContact(name, address, phone, city) {
    this.contactList.push({
      name: name,
      address: address,
      phone: phone,
      city: city
    }).then( newContact => {
      this.navCtrl.pop();
    }, error => {
      console.log(error);
    });
  }
}

Edit pages/add-contact/add-contact.html to add a form for creating a new contact.

<ion-header>
  <ion-navbar>
    <ion-title>addContact</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="add-contact">
  <ion-item>
    <ion-label stacked>Name</ion-label>
    <ion-input [(ngModel)]="name" type="text" placeholder="Fill yor first and last name"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Address</ion-label>
    <ion-input [(ngModel)]="address" type="text" placeholder="Fill your full address"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Phone</ion-label>
    <ion-input [(ngModel)]="phone" type="text" placeholder="Fill your phone number"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label stacked>City</ion-label>
    <ion-input [(ngModel)]="city" type="text" placeholder="Fill your city"></ion-input>
  </ion-item>
  <button block (click)="addContact(name, address, phone, city)"> Add Contact </button>
</ion-content>

It’s time for testing what we have done so far. Run your app in the browser.

ionic serve

Navigate to tab contact. For the first time, you will see a blank page with only “My Contacts” header. Then click the “+” button to add the new contact.

Ionic 2 Firebase CRUD - Add Contact Page

Fill out this form and click add contact button. This should be saved in Firebase database and redirect to contact page.

Ionic 2 Firebase CRUD - Contact List

If you are curious about what happens in Firebase database, just go to the Firebase console dashboard and go to the database menu. Your database must be like this:

Ionic 2 Firebase CRUD - Firebase Console Database

That it’s for now, next we’ll continue to part II for delete and update function.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks.

Loading…