Recently the Firebase platform got a complete redesign, including some new features and functions. As it’s still one of the most used cloud backends and with the soon to come Ionic 2 release candidate it’s about time to play around and build a little app using Ionic 2 Firebase Integration.
Good thing we have a great wrapper that makes life a lot easier: AngularFire2!
By using this library we can easily keep our data in sync with out cloud backend plus also easily embed authentication using email and password. Let’s find out how!
The Basic App and Firebase Setup
Before we start with the app, let’s create our Firebase app. Go to the new Firebase console and create a blank new project.
We need to copy some more strings from Firebase inside our app later, but we can actually find them directly on the overview page where it says “Add Firebase to your web app”. This is everything we will need for configuration.
Now it’s time for the Ionic app, so let’s start a new one including TypeScript and the AngularFire package:
ionic start devdactic-firebase blank --v2 --ts cd devdactic-firebase npm install angularfire2@2.0.0-beta.3-0930330 firebase@3.3.0 --save typings install file:node_modules/angularfire2/firebase3.d.ts --save --global && typings install ionic g page Login
Quick note: We use Ionic v2.0.0-beta.11 now!
This gives us a blank new Ionic 2 project including AngularFire and the Firebase lib. I specified those versions as there are currently many changes in all of those repositories. If you have problems after installing them, check out the complete template you can download at the top or leave a comment!
We also create a second LoginPage with the last command, which we will need soon.
Finally we get to the code, so let’s open the app/app.ts and insert:
import {Component} from "@angular/core"; import {Platform, ionicBootstrap} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import {LoginPage} from './pages/login/login'; import {FIREBASE_PROVIDERS, defaultFirebase, AngularFire, AuthMethods, AuthProviders, firebaseAuthConfig} from 'angularfire2'; @Component({ template: '<ion-nav [root]="rootPage"></ion-nav>' }) export class MyApp { rootPage: any = LoginPage; constructor(platform: Platform) { platform.ready().then(() => { StatusBar.styleDefault(); }); } } // Get he values from the overview page of your Firebase app ionicBootstrap(MyApp, [FIREBASE_PROVIDERS, defaultFirebase({ apiKey: "yourapikey", authDomain: "yourauthdomain", databaseURL: "yourdatabaseurl", storageBucket: "yourstoragebucket", })]);
As you can see we import a bunch of stuff from angularfire2, and in the provider section we can already configure it. Insert your Firebase URL here, it’s the only point where we ever need it!
The rest of this file is pretty straight forward, we only changed our initial Page to be the LoginPage which we have already created using the command line. Therefore we now need to work on our login view.
Building our Login
As said before, in this tutorial we will use a basic email and password authentication. This can be easily enabled inside Firebase, so go to your Dashboard and select your app. From the side menu navigate to Auth and find the point Sign in Method.
On that view we can enable all sort of logins, for now just make sure to turn the switch to on on the Email/Password card!
That’s everything we have to do from the Firebase side to enable authentication for our Ionic 2 with Firebase app.
We have previously generated our login page, so now go ahead and open app/pages/login/login.html and insert this:
<ion-header> <ion-navbar> <ion-title> Login </ion-title> </ion-navbar> </ion-header> <ion-content padding> <form> <ion-item> <ion-label floating>Email</ion-label> <ion-input type="email" name="email" [(ngModel)]="user.email"></ion-input> </ion-item> <ion-item> <ion-label floating>Password</ion-label> <ion-input type="password" name="password" [(ngModel)]="user.password"></ion-input> </ion-item> <div padding> <button block (click)="login(l)">Login</button> <button block (click)="registerUser()">Create New Account</button> </div> </form> </ion-content>
Nothing really special here, the only thing that might be new to you is the angular 2 style for a form. We actually don’t need any data model inside our controller for this, it’s all done on the fly!
Pretty cool, right?
So we got 2 actions, login with the inserted credentials or creating a new account from those. Both actions can be found inside our class for the Login, which is at app/pages/login/login.ts and which we edit now:
import {Component} from '@angular/core'; import {NavController, AlertController, LoadingController} from 'ionic-angular'; import {FirebaseAuth, AuthProviders, AuthMethods} from 'angularfire2'; import {HomePage} from '../home/home'; @Component({ templateUrl: 'build/pages/login/login.html', }) export class LoginPage { loader: any; user = {email: '', password: ''}; constructor(public nav: NavController, public auth: FirebaseAuth, private alertCtrl: AlertController, private loadingCtrl: LoadingController) {} public registerUser() { this.showLoading() this.auth.createUser(this.user).then((authData) => { setTimeout(() => { this.loader.dismiss(); }); let prompt = this.alertCtrl.create({ title: 'Success', subTitle: 'Your new Account was created!', buttons: ['OK'] }); prompt.present(); }).catch((error) => { this.showError(error); }); } public login() { this.showLoading() this.auth.login(this.user, { provider: AuthProviders.Password, method: AuthMethods.Password }).then((authData) => { this.loader.dismiss(); this.nav.setRoot(HomePage); }).catch((error) => { this.showError(error); }); } showLoading() { this.loader = this.loadingCtrl.create({ content: 'Please wait...' }); this.loader.present(); } showError(text) { setTimeout(() => { this.loader.dismiss(); }); let prompt = this.alertCtrl.create({ title: 'Fail', subTitle: text, buttons: ['OK'] }); prompt.present(); } }
We import FirebaseAuth which allows us to use the auth property to create and login users. It’s really that simple!
If an account is successful created, we show a little success popup to the user.
If we login successful, we just set the rootPage of the navigation to the HomePage, which will basically be then the only view of our app.
Additionally we have an alert for errors and also a little loading indicator to show progress to the user. All of this done in really a few lines.
You can now go ahed and already test your user creation and login functions. They should be working by now, so if you encounter any error up to here leave a comment below. Otherwise let’s continue with our actual data list.
Cloud Sync Ionic 2 with Firebase
All of the previous stuff has been pretty easy – and it will continue like this.
The actual goal of using Firebase or a Backend as a Service is to have great sync between the data stored on that database and our app. To achieve this from our app we only need a few line,s but first of all we need to define our database structure on Firebase, so again go into your app and select Database.
In the following view click on the 3 dots at the right end of the card and select Import JSON, like in the image below.
For the JSON file, take this simple pre filled Database structure:
{ "todoList" : { "0" : { "todo" : "My first Todo" }, "1" : { "todo" : "My second Todo" }, "2" : { "todo" : "My third Todo" } } }
This JSON simply describes an array called todoList with 3 items in it. So after the import, you should already see 3 items inside the Firebase database for your app.
How to Use Ionic 2 With Firebase – Fullstack, Bitch!
Click To Tweet
We continue again on the app side (Fullstack, bitch!) to retrieve our new created list of todos. We start with the view for our list, so open the app/pages/home/home.html and insert:
<ion-header> <ion-navbar> <ion-title> My Todos </ion-title> <ion-buttons end> <button (click)="createTodo()"> <ion-icon name="add"></ion-icon> </button> </ion-buttons> </ion-navbar> </ion-header> <ion-content class="home"> <ion-list> <ion-item-sliding *ngFor="let item of todoList | async"> <button ion-item (click)="openTodo(item)"> <ion-item-content> <h2>{{item.todo}}</h2> </ion-item-content> </button> <ion-item-options> <button danger (click)="removeTodo(item)"><ion-icon name="trash"></ion-icon> Delete</button> </ion-item-options> </ion-item-sliding> </ion-list> </ion-content>
Inside our view we have a navbar, which will display an icon of the current user and also a plus icon for adding todos to our list.
The main content consists of a simple list that iterates over our todoList
using the async pipe, which will automatically update our view once the array of Observable updates. Read more in the official documentation for AngularJS 2.
Our list item will then have the name of our todo, and also an option button which we can slide in where we can then remove the todo. Basic functionality, nothing special or new.
The more interesting stuff happens inside the Home class, so open the app/pages/home/home.ts and insert:
import {Page, NavController, AlertController} from 'ionic-angular'; import {FirebaseAuth, AngularFire, FirebaseListObservable} from 'angularfire2'; import {Component} from "@angular/core"; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { todoList: FirebaseListObservable<any>; constructor(public af: AngularFire, public auth: FirebaseAuth, public nav: NavController, private alertCtrl: AlertController) {} public createTodo() { this.editTodo(null, true); } public openTodo(todo) { this.editTodo(todo, false); } public removeTodo(item) { this.todoList.remove(item); } editTodo(todo, isNew: boolean) { let prompt = this.alertCtrl.create({ title: isNew ? 'Create Todo' : 'Update Todo', inputs: [ { name: 'title', placeholder: 'Title', value: todo ? todo.todo : '' }, ], buttons: [ { text: 'Cancel', role: 'cancel' }, { text: todo ? 'Update' : 'Add', handler: data => { if (isNew) { this.todoList.push({'todo': data.title}); } else { this.todoList.update(todo, {todo: data.title}); } } } ] }); prompt.present(); } ngOnInit() { this.auth.subscribe((data) => { if (data) { this.todoList = this.af.database.list('/todoList'); } }) } }
The start of the class happens at the end of the listing inside the ngOnInit
, because after the page is initialised we subscribe to the auth status of angularFire.
Why?
Because our user needs to be really signed in to read the data! If we actually are signed in, we set our public todoList
to this.af.list('/todoList')
which will trigger our Firebase for an list of objects inside the todoList bucket!
This will also automatically update our list, as it’s of the type FirebaseListObservable
.
To remove a todo from our list, we can simply call remove on our list, and everything will simply update in the background!
We have 2 events for opening or creating a todo, both do quite the same but when we edit a todo we need to gather the data we already have while we need to create a completely new entry if we select to add a todo.
Anyway, in the end there are only 2 functions that matter for those operations which are push and update, both can be simply called on our list with the object being the argument of the call.
Now run your app, watch the sync between your list and the Firebase database and simply feel awesome about what you did in nearly no time!
For a full video version this article watch the video below (and make sure to signup for my channel!)
Conclusion
I love the idea of having a backend database up in minutes, plus the ability to add social login features or special stuff like that in no time. The times are over where we would need an additional backend developer for a full blown backend – most of the time a simple BaaS can do the same or even better in a shorter amount of time and without big knowledge about complex backends. Working like this on front end backend just feels fast and good – Fullstack, Bitch!
Happy Coding,
Simon
The post How to Use Ionic 2 Firebase Integration For Cloud Sync and User Signup appeared first on Devdactic.