Book Image

Hybrid Mobile Development with Ionic

By : Gaurav Saini
Book Image

Hybrid Mobile Development with Ionic

By: Gaurav Saini

Overview of this book

Ionic is an open source, front-end framework that allows you to develop hybrid mobile apps without any native-language hassle for each platform. It offers a library of mobile-optimized HTML, CSS, and JS components for building highly interactive mobile apps. This book will help you to develop a complete, professional and quality mobile application with Ionic Framework. You will start the journey by learning to configure, customize, and migrate Ionic 1x to 3x. Then, you will move on to Ionic 3 components and see how you can customize them according to your applications. You will also implement various native plugins and integrate them with Ionic and Ionic Cloud services to use them optimally in your application. By this time, you will be able to create a full-fledged e-commerce application. Next, you will master authorization, authentication, and security techniques in Ionic 3 to ensure that your application and data are secure. Further, you will integrate the backend services such as Firebase and the Cordova iBeacon plugin in your application. Lastly, you will be looking into Progressive Web Applications and its support with Ionic, with a demonstration of an offline-first application. By the end of the book, you will not only have built a professional, hybrid mobile application, but will also have ensured that your app is secure and performance driven.
Table of Contents (9 chapters)

Angular 4, Ionic 3, and TypeScript

Many of us coming from the Angular 1 world to Angular 2 or 4 will surely see that it's an entire rewrite of the application and a steep learning curve. I felt the same when I initially started Ionic and Angular, but gradually as I read about the concepts of Angular, many of the problems we used to face in Angular 1 were automatically solved without any effort. Initially you will miss the old controllers, services, filters, and other concepts in Angular 1 and most importantly the navigation and routing. But when you dive deep into the topics you will find that corresponding modules such as component, providers, and pipe are available and that they can be used in similar ways. Navigation and router are also now used as push and pop mechanisms for navigating from one page to another page. In the initial beta versions of Ionic 2, we don't have proper URL-based routing as users can't land on a specific page in the application. But after a stable Angular-router is released it has been added to Ionic 2, which has opened the path for better support for progressive web apps, which will allow the same Ionic apps to be shipped as mobile web applications. Ionic 3 also added support for responsive grids, which will help when we will be building desktop applications. Lazy Loading is another important feature added, which reduces the initial loading time of the application. Still, as Ionic 3 is in initial days, we can expect these features to become a lot more stable. As, we know Ionic 2 and 3 did not have any major framework changes, so initially we will be comparing Angular 1 and 2 in this chapter so it helps users understand the difference and how they can migrate to the latest Ionic versions.

Angular and Ionic myths

As you go forward, you will hear many myths that are not true in respect to Angular 2 or upgrading to Angular 4. One of the most common is the Angular 4 doesn't support two-way data binding, which is not true. The Angular team has made sure that we use forms as simple as we use in Angular 4, they just have a new syntax:

      [(property-name)]="expression"

<input type="text"
[(ngMmodel)]="model.name" />

We still have two-way data binding. Although, to improve the Angular digest cycle and performance by default, we don't use two-way data binding. It uses a unidirectional binding that we can extend to two-way binding when we require it. You can refer to Angular template syntax to demystify all other syntax's and their uses available with Angular 4.
Ionic lack URL navigation is another discussion going on at the Ionic forum. Again this is also partially correct; because Angular-router was not stable enough, the Ionic team decided to remove it in the initial beta version. As of now, Angular-router is stable and will be in Ionic. The Ionic team understands how critical it is to have a proper routing mechanism and to make a developer feel at home while moving towards Ionic 3.
Upgradation is entirely rewritten: Angular 2 is itself rewritten, but you don't have to rewrite your app also. Initially when I started I felt the same and thought that we had to redevelop our current application. But there are many tools and documentation (http://ionicframework.com/files/Ionic2Migration.pdf ) available for a smooth upgrade from Ionic 1 to Ionic 2 or 3. You just have to be careful as if you have a complex application then you might have to do many things manually. But one thing is for sure that upgrading the application will surely not take that much time when you build the same application from scratch if you have proper expertise and a concept of Angular 2. One of the reasons behind this is that you already have a running application where you just have to assemble the moving parts in different ways, as most of the application logic will be same.
Personally, my learning process with Ionic didn't think too much about I upgrading to a new version. Rather I took it as new improved concepts that came in new Angular versions, designed to ease the learning and understanding.

Mapping Ionic 1 to Ionic 3

Life will be really easy for any developer who can easily understand the mapping of different concepts that were in Angular 1 and how they are
catered to in Angular 4. Also, I am sure that most of the questions will be answered automatically.

Controllers match components

Components are the backbone of Angular and Ionic applications; you will see that almost everything is a component. You can compare controllers in Angular 1 to components in Angular 4. In controllers we used to define most of our code's logical part. We used to register the controllers with our main module. Now, in a similar way, we define our code in components in Angular 4 and if required we can export that Component class:

    // Angular & Ionic 1

angular.module('wedding.controllers', [])
.controller('LoginCtrl',
function($scope, CategoryService) {
// controller function and DI of CategoryService
}
);

// Angular 4 & Ionic 32

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
templateUrl: 'build/pages/catalog/categories.html'
})
export class CategoryPage {
// DI of NavController for navigation
constructor(private navCtrl: NavController) {
this.nav = navCtrl;
}
}

We have dependency injection in Angular 1 as controller function arguments, while in Angular 4 we pass it inside the constructor function. Many other things such as the IIFE syntax, which we have to define in Angular 1 for keeping out controller code of the global namespace, now are not required in Angular 4 because ES 2015 modules handle name spacing for us. Also, as you can see, we have exported the CategoryPage class, we can now import it wherever this module is required.
Another major change is that $scope is replaced by the this keyword. $scope had many performance issues and already in Angular 1 developers have reduced the usage of $scope.

Filters match pipes

Angular 4 pipes are similar to what we use Filters for in Angular 1. Pipes provide the same formatting and transformation for data in the template. Almost all of the inbuilt filters that Angular 1 has correspond to pipes in Angular 4:

// Filter - Angular 1 
<td>{{movie.price | currency}}</td>

// Pipes in Angular 4
<td>{{movie.price | currency:'USD':true}}
</td>

Due to performance reasons, filter and orderBy filters have been removed from Pipes, although you can at anytime build a custom pipe if similar code is reused in multiple templates.

Services match providers

Services and Factory are important parts of Angular 1x where we communicate with a remote server for data. We used to define APIs call inside factory functions that controllers calls for fetching data from the servers:

 // Factory method in Angular 1x 

angular.module('wedding.services', [])

// DI of $http for HTTP calls to servers
// $q for promises
.factory('CategoryService', function ($http, $q) {
var catalog = {};

catalog.getCategories = function () {
// here we will call APIs
}
})

Now you will see how we have migrated our code to Angular 4 providers. The same getCategories() method that was inside factory in Angular 1, will now be moved inside the CategoryData() class in Angular 4:

 
// Provider in Angular 4

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class CategoryData {

constructor(private http: Http) {}

getCategories() {

return new Promise(resolve => {
// We're using Angular Http provider
to request the data,
// then on the response it'll map the
JSON data to a parsed JS object.
// Next we process the data and
resolve the promise with the new
data.

this.http.get('www.veloice.com/data.json').subscribe(res
=> {
// we've got back the raw data, now
generate the core schedule data
// and save the data for later
reference
this.data = this.processData(res.json());
resolve(this.data);
});
});
}
}

You will notice that the Provider class has a @Injectable decorator. This decorator lets Angular 4 know that the specific class can be used with the dependency injector.

TypeScript comes to the rescue

TypeScript is basically a superset of Javascript, which is a statically typed language. TypeScript does similar to what LESS or SASS does to CSS. TypeScript compiles to Javascript and has almost the same syntax. Anyone from an object-oriented world will find it really, familiar with concepts such as classes, constructors, inheritance, and interfaces.
Many developers will be confused with all these keywords such as ES5, ES6, TypeScript, AtScript, and many others. JavaScript is a community-driven language, and accordingly, browser manufacturers implement those features that are mostly used. Currently, ES5, that is ECMAScript 5, is a standardization by ECMA international. ES6 and ES7 are future standards of JavaScript with tons of new features. We can develop applications in ES6 and ES7 directly with the use of Babel, which is a transpiler. Transpilers are source-to-source compilers that take input in one programming language and output the equivalent code in another language. Although it is recommended to use TypeScript as the majority of work going on in the Ionic community is on TypeScript. Also, you will easily get resources and community help.
When we start a new Ionic 3 project it create the project with TypeScript, although in Ionic 2 and CLI v2 we had option for creating project with TypeScript. As mentioned, we should use TypeScript because, as the project will become a large scale project, things will be easier to maintain and understand. I want to clear up one important point here about Angular 4: whether it's TypeScript or ES 6 whenever you run the Ionic server, our app folder is transpiled into ES5, as that is what currently all major browsers support. There are many new features available in TypeScript that we will be mainly using in our Ionic or Angular applications. Some of them are listed here:

  • Class and module support
  • Static type-checking
  • Similar syntax to other object-oriented languages
  • ES6 features such as template string support
  • Decorator, annotation support, and dependency injection
  • Arrow functions