Ionic CRUD operation on Firebase through AngularFirebase 2

W e can use Firebase to store data. With Firebase we can easily do CRUD and it provides login with the different option. We are creating Ionic apps with firebase and we will be doing following as

  1. Login and register user in our app through Firebase.
  2. Register user can create and view Shopping List through CRUD on Firebase database.

Step 1:  Creating our app from blank template

We can use SDK Firebase package, but angularfire2 are easier to code in our project.

ionic start firebaseAuth blank 
npm install angularfire2 firebase --save

 

Step 2: Creating / Configuring Firebase

We need to create a project, as we have three option to select as Android, Apple and web apps. As our Ionic project, we have to select the web. Add authentication to our project, click on Authentication and select option sign in options as Email and password as 

Firebase provides a lot of authentication option as login through social network authentication eg Facebook and Google etc.  We can control the access of Firebase database inside the firebase through setting rules. If we are not using any authentication then we set all user can read/write as in

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

 

Step 3: Configure our app.module.ts.

Before we configure, first create a file app.firebase.config.ts file containing the Firebase API. Add the following code in app/app.firebase.config.ts

 export const FIREBASE_CONFIG = {
    apiKey: "..",
    authDomain: "...",
    databaseURL: "...",
    projectId: "..",
    storageBucket: "",
    messagingSenderId: "7..."
  }; 

This information we will get from our Firebase project and add this code in app.module.ts file. Add the following code in app.module.ts file

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

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { RegisterPage } from '../pages/register/register';
import { LoginPage } from '../pages/login/login';
import { HttpModule } from '@angular/http';
import { AngularFireModule} from 'angularfire2';
import { AngularFireDatabaseModule} from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { FirebaseService} from '../providers/firebase-service';
import { FIREBASE_CONFIG } from "./app.firebase.config";

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

 

Step 4:  Create Firebase Service provider 

Create a Firebase service provider to access/ CRUD operation on Firebase database. First set the database rule to allow all user to read/write true. We will control the access later through creating Login/Register page

ionic g provider firebaseService

Add the following code in src/providers/firebase-service.ts

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

@Injectable()
export class FirebaseService {

  constructor(public afd: AngularFireDatabase) {}

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

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

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

}

Here we are implementing CRUD operation on our Firebase database, we can easily understand the code of service.

 

Step 5: Create UI of our data on Home page

We will use the home page to display/ UI to allow the user to create/delete the shopping list. Add the following code in src/home/home.html

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

<ion-content padding>
  <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>

We are creating FirebaseListObservable in src/home/home.ts file as

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


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

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

  addItem(){
    this.firebaseService.addItems(this.newItem);
  }

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

}

 

Step 6: Adding Login /Register in Apps

Firebase supports login and authentication internally and also provides support for integrating with social login providers. Most applications need some kind of login mechanism internally; with Firebase it’s super easy to set this up. Whenever we login using Firebase a session is created and a unique ID uid is returned by Firebase, which is distinct across all providers and never change for a specific authenticated user.

We will create two-page Login and Register page as

ionic generate page Login
ionic generate page Register

Now set the login page to root and edit root page from home to login in app.component.ts file

...
import { LoginPage } from '../pages/login/login';
..

export class MyApp {
  rootPage:any = LoginPage;
  ....
}

 

Step 7: Creating User Model

Inside src folder create a new folder called models and add the new file for user model as a src/models/user.ts. Add the following code

export interface User{
    email: string;
    password : string;
}

 

Step 8: Create UI and typescript code for Login/Register page

Add the following code in src/pages/login/login.html file

<ion-header>
  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <ion-item>
    <ion-label>Email Address</ion-label>
    <ion-input type="text" [(ngModel)]="user.email"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Password</ion-label>
    <ion-input type="password" [(ngModel)]="user.password"></ion-input>
  </ion-item>

  <button ion-button (click)="login(user)">Login</button>
  <button ion-button color="light" (click)="register()">Register</button>
</ion-content>

Add the following code in src/pages/login/login.ts file, as for login we have to create service in real apps, as for this example we will put Firebase authentication in login.ts file only.

import { Component } from '@angular/core';
import {  NavController, NavParams } from 'ionic-angular';
import { User } from '../../models/user';
import { RegisterPage } from '../register/register';
import { AngularFireAuth } from 'angularfire2/auth';
import { HomePage } from '../home/home';


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

  user = {} as User;

  constructor(private angFireAuth:AngularFireAuth, public navCtrl: NavController, public navParams: NavParams) {}

 async login(user: User){
   try{
    const result = this.angFireAuth.auth.signInWithEmailAndPassword(user.email, user.password);
    if(result){
      this.navCtrl.setRoot(HomePage);
    }
   }
   catch(e){
     console.error(e);
   }
 }

 register(){
  this.navCtrl.push(RegisterPage);
 }

}

Note : When the user passes the authentication, we will redirect the user to home page, where home page containing the shopping list. In the login page, we have two buttons one for login and one for register new user. The information of the new user will be stored in Firebase database. Clicking on Register button on login page will navigate to the regiseter page.

Add the following code in src/pages/register/register.html file 

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

<ion-content padding>
  <ion-item>
    <ion-label>Email Address</ion-label>
    <ion-input type="text" [(ngModel)]="user.email"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Password</ion-label>
    <ion-input type="password" [(ngModel)]="user.password"></ion-input>
  </ion-item>

  <button ion-button (click)="register(user)">Register</button>
</ion-content>

Add the following code in src/pages/register/register.ts file 

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { User } from '../../models/user';
import { AngularFireAuth } from 'angularfire2/auth';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {
  user = {} as User;

  constructor(private angFireAuth: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams) {
  }

  async register(user: User){
    try {
      const result = await this.angFireAuth.auth.createUserWithEmailAndPassword(user.email, user.password)
      this.navCtrl.push(LoginPage);
      console.log(result);
    }
    catch(e) {
      console.error(e);
    }
    
  }
}

In real application we have to create separate Firebase service code in service folder, for now just for example we are keeping service code with register/login page.

Step 9: Modify the home page

Once valid user login, we will redirect to home page, here we add ToastController.

Add the following code modify the code in home.ts file, we have added ToastController to display the message below on above image.

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

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

  constructor(private angFireAuth: AngularFireAuth,  private toast: ToastController, public navCtrl: NavController, public firebaseService: FirebaseService){
    this.shoppingItems = this.firebaseService.getShoppingItems();
  }

  addItem(){
    this.firebaseService.addItems(this.newItem);
  }

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

  ionViewWillLoad(){
    this.angFireAuth.authState.subscribe(data => {
      if(data && data.email && data.uid){
        this.toast.create({
          message: `Welcome to APP_NAME', ${data.email}`,
          duration: 3000
        }).present();
      }
      else{
        this.toast.create({
          message: `Couldn't find authentication, ${data.email}`,
          duration: 3000
        }).present();
      }
    });
  }

}