Ionic 2 technologies

November 20, 2016, 9:18 pm Categories:

Categories

Ionic 2 brought with it many changes - not least of which was the adoption of Angular 2 and TypeScript.

The following sections provide some background information and examples for each of the core technologies that underpin version 2 of the Ionic framework.

TypeScript

A superset of the JavaScript programming language - basically JavaScript but with additional features and functionality not found in that language (until ECMAScript 6 that is) TypeScript was developed by MicroSoft as a means to provide stricter object oriented programming and class based object generation for JavaScript developers.

To understand why TypeScript is so important we have to understand one of JavaScript's strengths, and, ironically, its weaknesses...

Its flexibility.

If we wanted to create an object in JavaScript there was, until ECMAScript 6, no one single way in which to do this. This meant we could create an object, for example, using any of the following approaches:

// 1 - Using the Object constructor
var myObj = new Object();
myObj.property1 = "Value 1"
myObj.property2 = "Value 2";
console.log("Value is: " + myObj.property1);



// 2 - Using an object literal
var myObj = { 
   property1 : "Value 1",
   property2 : "Value 2"
};
console.log("Value is: " + myObj.property1);



// 3 - Using a factory function
function myObj()
{ 
   return {
      property1: "Value 1", 
      property2: "Value 2"
   }
};
var o = myObj();
console.log("Value is: " + o.property1);



// 4 - Using prototypes
function myObj()
{ 
   this.property1 = "Value 1", 
   this.property2 = "Value 2"
}

myObj.prototype.getProperty1 = function()
{
   console.log("Value is: " + this.property1);
}

var o = new myObj(); 
o.getProperty1();



// 5 - Using self-invoking function expressions
var OBJ = (function() 
{
   var _privateMethodOne = function()
   { 
      _privateMethodTwo(); 
   },

   _privateMethodTwo
   { 
      console.log('Hello!'); 
   };

   return {
      publicMethodOne  : _privateMethodOne
   }
})();

OBJ.publicMethodOne();

This flexibility isn't necessarily a bad thing but it can cause problems in terms of non-standardised ways of working (particularly if you have to pick up another developer's code for a project) and managing codebases between teams (I.e. structuring projects for scalability, performance optimisations etc).

Similarly, JavaScript allows variables to be mutable as demonstrated in the following example:

var prop = 2; 
console.log(typeof prop); 
// Prints: number


//Now assign a different value and data type to the variable
prop = "Man";  
console.log(typeof prop);
// Prints: string

This is pretty bad as such flexibility can introduce unexpected bugs in the logic flow of your code that can cause endless headaches trying to diagnose.

TypeScript heads off both of the above problems by employing, amongst other features:

  • A class based approach to generating objects
  • Strict data typing so that values cannot be changed from one data type to another

Both of which are demonstrated in the following TypeScript code snippet:

class Person {
   public gender: string;

   public constructor(genderType: string)
   { 
      this.gender = genderType; 
   }

   public works(durationOfWork: number) 
   {
      console.log(`This ${this.gender} worked ${durationOfWork} hours.`); 
   }

}

We'll cover TypeScript in more depth over subsequent articles.

Angular 2

As the underlying front-end development framework for Ionic 2 the latest iteration of Angular brings with it the following features:

  • Web components (packaged bundles of HTML, Sass & TypeScript)
  • Modules
  • Built on TypeScript
  • Improved form handling/validation options
  • Improved animations (built on top of the Web Animation API)
  • Use of annotations (to provide component metadata)
  • Improved dependency injection
  • Improved template syntax

A sample Angular 2 script (using the TypeScript language) might look something like the following:

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

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

  public pages : Array<{title: string, thumb: string, description: string, link: any}>;
  public isSuccess: boolean;
  public isError: boolean;
  public isWarning: boolean;  
  public canProceed: boolean;

  constructor(public navCtrl: NavController) {

  } 


}

Here we can see a number of Angular 2/TypeScript features:

#1 - Use of modules

Import statements at the top of the script allow different classes to be imported for use within the class.

#2 - Annotations

The @Component metadata declaration is used to signal that the class is a component.

#3 - export

The export module allows the HomePage class to be available for import and use in other classes

#4 - Access modifiers

These define the visibility of class members - I.e. whether they are globally available, able to be sub-classed or only available within that class.

In the above code we are using the public keyword to show the member is able to be accessed outside of the HomePage class.

TypeScript offers 3 levels of access modifier:

  • public (available outside of the class)
  • protected (available inside the class and any related sub-class)
  • private (available only inside the class where it is defined)

#5 - Type assertions

Used to define the data types for members within the class.

In the following example we have the following type assertions for the different class properties:

  • Array (with type assertions for each stated key)
  • boolean
public pages : Array<{title: string, thumb: string, description: string, link: any}>;
public isSuccess: boolean;
public isError: boolean;
public isWarning: boolean;
public canProceed: boolean;

#6 - constructor

Use of the constructor function to initialise the class upon creation

#7 - Dependency injection

Dependency injection, or DI, is a coding pattern that allows a class to access dependencies from outside of itself, by "injecting" them into the constructor.

In the initial code snippet for this section the class constructor, passes in an instance of the NavController component (which was imported at the top of the script) and stores that in public property named navCtrl.

Similarly, within the templates used in our Ionic 2 apps we can implement angular 2 features such as event binding, loops and handlebar syntax as demonstrated in the following code snippet:


   {{ item.title }}

We'll be covering different aspects of the Angular 2 framework, in relation to its usage within Ionic 2, over subsequent articles.

Apache Cordova

As Ionic 2 is built on the freely available Apache Cordova framework developers have access to the following:

  • Cross platform publishing capabilities
  • Extensive plugin API

This might seem pretty standard now but the ability to develop for iOS, Android & Windows Phone (to name but a handful of supported platforms) from only a single codebase, using HTML and JavaScript, was pretty groundbreaking at the time Apache Cordova was first released.

This allowed web developers to start building native-like mobile apps without having to learn Objective C, Java or C# - and not have to maintain 3 separate codebases for the same project.

Impressive to say the least.

Similarly Cordova's Plugin API exposes JavaScript methods allowing developers to hook into and use functionality such as device alerts, importing address book details, obtaining geolocation information or determining their device network connection.

A full list of Cordova plugins is available here.

Ionic Native

Introduced as an upgrade to ngCordova, Ionic Native provides a repository of ES5, ES6 and TypeScript compatible Cordova plugins for use in Ionic 2 apps.

Native events are able to trigger change detection in the underlying Angular 2 framework through the use of Promises/Observables which Ionic Native implements to manage plugin callbacks.

This is hugely important as this common interface allows the different technology layers within Ionic 2 to "play nicely" with one another.

Plugins range from Calendars, Date Pickers and Google Maps to In-app Purchases and social media utilities, to name but a handful, making this a massively useful tool in the Ionic 2 ecosystem.

More on Ionic Native here.

Sass

As Ionic 2 implements web components (courtesy of the underlying Angular 2 architecture), Sass is the default choice to provide the basis for all application style rules; in both pre-existing Ionic components and those generated by developers.

This was a pretty smart move on the part of the Ionic team, given Sass's adoption as an industry standard, as Sass allows developer's to craft CSS using, amongst other features:

  • Variables and similar programming operators (such as functions and loops)
  • Mixins (collected snippets of CSS declarations that can be reused throughout an application)
  • Math operators (addition, subtraction, division, multiplication and the modulus operator)
  • nested rules and ineritance

More on Sass here

Ionic CLI

Ionic 2 comes with a powerful command line utility allowing developers to create applications, install mobile vendor platforms, generate components and publishing apps to devices, amongst other functionality, such as:

// List ALL installed plugins for the app
ionic plugin ls

// Add a service to your Ionic app
ionic g provider name-of-service-here

// Add a pipe to your Ionic app
ionic g pipe name-of-pipe-here

Additionally, when developing our apps the CLI converts, or transpiles, the TypeScript to ES5 compliant JavaScript so that devices & browsers can parse the application logic.

We'll cover the Ionic CLI in a subsequent article.

Summary

That wraps up our discussion of the core technologies used within Ionic 2 and, if you're new to version 2 of the framework, it might seem a little overwhelming at first.

Forthcoming blog articles will cover the above in more depth and you can also find more information and examples of how these technologies are implemented in Ionic 2 through my e-book: Mastering Ionic.

Tags

Categories

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.

Top