Using firebase in ionic 2

Using firebase in ionic 2

Firebase is a platform for mobile and web apps. There’s three main services to Firebase:

  1. Real Time database
  2. Authentication
  3. Static Hosting

In this tutorial we are using latest version of ionic that is ionic 2. New version of ionic was released with many new features with resolved many bug

Creating Firebase Project

  1. Go to https://console.firebase.google.com/
  2. Create New Project
  3. Go to Project->click on Overview
  4. Click on “Add Firebase to your web app” icon
  5. Copy the snippet from popup which was used in ionic app

Changing database Rule

  1. Go to your firebase app->Database
  2. Then click on “Rules” Tab and update rule to below and click on publish

Using this rule anyone can read data and write data. Check out more about Database Rules click here.

Before We start make sure your ionic is updated with ionic 2. If not then update ionic with following command

Let’s start with creating fresh new ionic 2 project

Got to project folder

Adding platform

Note that if you have to make ios app then you required mac.

Go to firbasedemo/src/index.html

Add the firebase script which was getting from above step 5 while “Creating Firebase Project “.

In this firebase example we are saving user’s name and email to firebase and retrieving the users data from firebase.

Open firbasedemo\src\pages\home\home.ts.

In the above code there is constructor() in which we are fetching users data from the firebase.

Here  _db is reference of firebase database .  To read data at a path and listen for changes use the  on() method.

You can use the value event to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes.

The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null.

do forEach loop of dataSnapshot for getting childSnapshot and push that childSnapshot.val() to users array one by one.

After that there is insertdata() method for storing users name and email to firebase database. For storing data to firebase there is push method. Here id is unique number which was stored in firebase.

Let’s move to html stuff

Go to firbasedemo\src\pages\home\home.html.

Here is  insert button which fire insertdata() function when button is pressed and after that displaying user’s name and email from users array one by one using ngFor.

Let’s check the app is working or not in the browser using below command.

 

Using firebase in ionic 2

 

 

Leave a Reply