How to Hide Tab Bar and Handle hardware Back Button in Ionic 3

Hey Guys, In this Post we will take a look at How to Hide Tab Bar and Handle hardware Back Button in Ionic 3 application. We will take a look at how we can add page specific hardware back button actions and How can we Hide Tab Bar on a specific page in our Ionic application. I have a detailed post showing you how you can navigate between pages with or without ion-tab-bar in Ionic. In this post, our focus will be on handling the hardware back button and hiding/removing Tabs from specific pages.

A thing to note is that the hardware back button is an Android-only thing. iOS does not have a back button and the code that we will use will not fire in iOS.

Lets Talk about Ionic Tabs, as we know the tabbed interface is a very popular pattern on all mobile platforms. This interface is especially popular on iOS where it is encouraged by Apple’s design language over a side menu. It has the advantage that the user can see all of the options available to them whereas a side menu’s options are hidden by design.

Ionic has a very simple tabs directive allowing you to implement these kind of interfaces with lots of options for different styles (icons only, text only, text and icon). now we will start with hiding the ion-tab-bar in specific pages in ionic 3 application.

Hide Tab Bar

Hiding or removing ion-tab-bar in ionic is so easy. I came across this as i was working on a project recently, it is just the single line of code for this. The things you need to understand is the behaviour of how it works.

Notice that each<ion-tab> binds to a [root] property, just like <ion-nav> in the Navigation section. That is because each is really just a navigation controller. This means that each tab has its own history stack, so here the main question arrives how do we take the navigation control in our hands and hide tabs on specific pages as we want. The answer can be reached through many methods but for doing that we need to understand the navigation stack, take a look at it here.

<ion-tabs> creates a history stack for it’s each tab which is a path in which the tabs are being navigated. We use navigation controllers here to navigate to pages in our app. At a basic level, a navigation controller is an array of pages representing a particular history of a Tab.

The current page is the last one in the array, or the top of the stack if we think of it that way. Pushing a new page onto the top of the navigation stack causes the new page to be animated in, while popping the current page will navigate to the previous page in the stack.

For hiding ion-tab-bar on a specific page or view we need to navigate from an overlay component. Here we’ll get a reference of the root NavController in our app, using the getRootNav() method.

So by this method we will navigate to the new child page and still keep our navigation stack history. Isn’t it awesome? Now let’s make a proper example for it to make it more understandable.
As we know there are some pages in every application in which we couldn’t afford display the Menu-bar or the ion-tab-bar with pages like Login, Signup or some other pages.
So understanding that we are going to create two extra pages in our ionic project.
Login Page
Child1 Page
Now we want to Hide the ion-tab-bar at the Login and Child1 Page which is the child page for our ion-tab with the selectedIndex “0” i.e. Home Page. lets write some code to add and config these.

First of all we create a new ionic project and the extra pages. We do that by running the following command in terminal/command prompt.

$ionic start hideTabPage tabs
$cd hideTabPage
$ionic g page Login 
$ionic g page Child1

Now by default the tab.html content may look like this code below

<ion-tabs>
 <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home" ></ion-tab>
 <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>
 <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab>
</ion-tabs>

We can use the selectedIndex property to set the index on the element. so we add a selectedIndex number for the tabs to init the start level page and also give a class-name to the ion-tabs like this.

<ion-tabs [selectedIndex]="mySelectedIndex" class="tabs-icon-text" id="tabs">

Now we will specify the indexing of tabs in its constructor as below

 this.mySelectedIndex = navParams.data.tabIndex || 0;

As we want to set the Login page on the app start we change the rootPage in app.component.ts and add these pages in app.module.ts .
app.module.ts

import { LoginPage } from '../pages/login/login';
import { Child1Page } from '../pages/child1/child1';
import { TabsPage } from '../pages/tabs/tabs';
 .
 .
declarations: [
 HomePage,
 LoginPage,
 Child1Page,
 TabsPage,
 .
 ],
entryComponents: [
 HomePage,
 LoginPage,
 Child1Page,
 TabsPage, 
.
 ],
 

app.component.ts

export class MyApp {
 rootPage:any = LoginPage;

Now let’s take a look at Login Page, as it is the root page for our application.

login.ts

Login page is redirecting to TabsPage, this page is configured with home, contact and about pages. Here we are going to use the navigation with the overlay components so the login view doesn’t get the ion-tab-bar and for this we are using  getRootNav() here to navigate LoginPage to the TabsPage.

import { Component } from '@angular/core';
import { NavController,App } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class Login {

  constructor(public navCtrl: NavController,
              public app: App //necessory for using the getRootNav
   ) {}

  login(){
    // Your app login API web service call triggers 
   this.app.getRootNav().setRoot(TabsPage, {}, {animate: true, direction:  'forward'});  
  }
}

by using setRoot here we are clearing the previous navigation stack history, as it is the rootPage of the application.

home.html
Home page with logout button and navigation to Child1 Page.

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

<ion-content padding>
  <h2>Welcome to HideTab Project</h2>
  <h3>for more content <button ion-button (click)="goToChild1()">click  here</button> </h3>
  <button ion-button color="primary" (click)="logout()">Logout</button>
</ion-content>

home.ts
Logout action to navigation to Login page and Read more action to Child1 Page. here we have the ion-tab-bar as it is the root component of the ion-tabs but when we logout from this page and navigates back to the LoginPage, we need to make sure that the navigation stack doesn’t keep history otherwise there will be an ion-tab-bar on the login page.

And on the other side with the ChildPage we still want to keep the navigation stack history so that we can get back there but with ion-tab-bar we work same as Logout function.

So what could be the difference between these two to handle these different conditions? Let’s find out here.

import { Component } from '@angular/core';
import { NavController, App } from 'ionic-angular';
import { LoginPage } from '../login/login'; 
import { Child1Page } from '../child1/child1';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public app: App) {

  }
goToChild1(){
           //navigating to ChildPage1
           this.app.getRootNav().push(ChildPage1);
  }
logout(){
        // Remove API token 
        const root = this.app.getRootNav();
        root.popToRoot();
  }
}

in home.ts we used  push with goToChild1() because to navigate to a single item from a tab, but still keep navigation history the piece we needed was this.app.getRootNav().push().

Now add android Platform to your application and run it.

$ionic cordova platform add android 
$ionic cordova run android

So here we got the hidden ion-tab-bar for any page we want in our app but there is still something left in here and that is handling hardware back button on the TabsPage.

Handling Hardware Back Button

This Section is all about how to handle the back button in Ionic 3.
The main issue of a hardware back-button is always a lousy timing. No matter how capable they are, application users will, sooner or later, unintentionally trigger a back-button event. This is something we want to prevent, as, no matter how perfectly configured, this act may deteriorate usability of our application. For example, it may lead to application termination, and the last thing we want to do is to force application users out.

Here you are going to learn how can we use RegisterBackButtonAction function of Ionic Framework to take full control over back-button triggering.

We are going to use the previous project we created for tabs here also. so lets look at the main component of the application where we are going to use registerBackButtonAction function. this implementation is really straightforward only thing we need to use here is this code.

platform.registerBackButtonAction(() => {
});

So let’s go to the central point of our application and start implementing this code.

modify app.component.ts : 

import { Component, ViewChild } from '@angular/core';
import { Platform, App, AlertController, Nav, IonicApp } from 'ionic-angular';
import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';

@Component({
 templateUrl: 'app.html'
})
export class MyApp {
 rootPage:any = LoginPage;
 @ViewChild(Nav) nav: Nav;

constructor(private platform: Platform,
 private alertCtrl: AlertController,
 private app: App,
 private ionicApp: IonicApp)
 {

  platform.registerBackButtonAction(() => {
   let navView = app.getActiveNav();
   let activePortal = this.ionicApp._loadingPortal.getActive() ||  this.ionicApp._modalPortal.getActive() || this.ionicApp._toastPortal.getActive() || this.ionicApp._overlayPortal.getActive();
//activePortal is the active overlay like a modal,toast,etc 

   if (activePortal) { 
      activePortal.dismiss();
      return; 
   } else if (this.menuCtrl.isOpen()) {
      // Close menu if open 
      this.menuCtrl.close();
      return; 
   }
   let view = this.nav.getActive();
   // As none of the above have occurred, its either a page pushed from menu or tab 
   let activeVC = this.nav.getActive(); 
  //get the active view 
   let page = activeVC.instance; 
  //page is the current view's instance i.e  the current component I suppose 

   if (!(page instanceof TabsPage)) {
 // Check if the current page is pushed from a menu click 
    if (this.nav.canGoBack() || view && view.isOverlay) {
     if(activeVC.name=='TabsPage'){
       console.log("You can't go back"); 
     }else{ 
       this.nav.pop(); 
//pop if page can go back or if its an overlay over a menu page 
       this.showAlert(); 
     } 
    } else {
       this.showAlert();
    } 
    return; 
   } 
   let tabs = this.app.getActiveNav(); // So it must be a view from a tab.   The current tab's nav can be accessed by this.app.getActiveNav(); 
   if (!tabs.canGoBack()) {
    this.showExitAlert();
    navView.parent.select(0); 
   } 
   return tabs.pop(); 
  }, 0);
 }//constructor closed
 showAlert(){
  //put some alert code here
 };
}

this is the full code  for the registerBackButtonAction function.  Let me explain it in parts.

 platform.registerBackButtonAction(() => { 
 let navView = app.getActiveNav(); 
 let activePortal = this.ionicApp._loadingPortal.getActive() ||  this.ionicApp._modalPortal.getActive() || this.ionicApp._toastPortal.getActive() || this.ionicApp._overlayPortal.getActive();

here we declare variable navView for getting the info about the active view on the application and activePortal is the active overlay component which checks the state of the condition either loading, modal, toast or overlay component.

 if(activeVC.name=='TabsPage'){
    console.log("You can't go back"); 
  }else{ 
    this.nav.pop(); 
    this.showAlert(); 
  } 

This is the code for the restriction of the hardware back button, it says if the active view is equals the TabsPage or any page you want to restrict, the registerBackButtonAction restricts the back button key that it stops working, else-wise in any other condition it pop out the page to the previous one in its navigation stack.

 if (!tabs.canGoBack()) {
  navView.parent.select(0);
  this.showExitAlert(); 
 } 
 return tabs.pop();

This section represents that if the tabs can’t go back much further in the application then the function will select the root view of index “0” which we declared at the start i.e. the selectedIndex of ion-tabs(HomePage). And finally the function ask for an logout alert or exit alert from the application.

This is how we can deal with both the conditions of how to Hide Tab Bar and Handle hardware Back Button in Ionic 3 in a very easy and simpler way.

If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don’t like something about this blog, if something is bugging you, don’t like how I’m doing stuff here, again leave me a comment below.

Thanks.

 

How to Install and Set-up MySQL with NodeJS in Ubuntu

In this Post we are going to see How to Install and Set-up MySQL with NodeJS in Ubuntu and creating connection of NodeJS with MySQL database using express framework. As we know NodeJS has done dramatic increase in adoption in the back-end side since it allows JavaScript uses in back-end as well as in front-end and MySQL in NodeJS is used to Fetch and post data from database.

Let’s get started now.

Installation:

>>sudo apt-get update
>>sudo apt-get install mysql-server

Run these commands in your terminal, now during installation You will be asked to set up root password. Make sure to remember the password or make note of it because you will be using every time you enter the database.

now You can check MySQL version

>>mysql --version
mysql Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using EditLine wrapper

Now the Installation part is done. now Let’s Start the MySQL Services

>>service mysql status

This command will show us the status of the MySQL and it will also Starts the services of the database.
If in any case this gives unknown error use this:

>>sudo service mysql start

Login into MySQL

Now login into MySQL cli with the following command:

mysql -u root -p

this will ask for the root password which we set during the time of installation.
enter the correct password and now you are logged in into the MySQL database.

Creating a Database

Creating a database is so easy as working in MySQL just run this command to create a Database in MySQL.

mysql> create database DbName;

Here “DbName” is the name of the database you can give your database any name you want.
If you want to confirm the existence of your database, you can just run the following command:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| DbName             | 
| performance_schema | 
| recorder           | 
| sys                | 
+--------------------+ 
6 rows in set (0.00 sec) 

Now for using a particular MySQL database

mysql> use DbName;

Now exit MySQL cli using “exit” command.

Now we are gonna work in NodeJs for adding MySQL in it. To learn more about NodeJS go to our previous post Integrating NodeJS server into an Ionic Application.

Installing Dependencies

Will going to use following node modules for handling session
Express
Body parser
MySQL

>>npm install express body-parser mysql

Now we have created a package.json file that will install all required dependencies. have a look,

package.json

{
 "name": "Adding-Mysql ",
 "version": "0.0.1",
 "main": "server.js",
 "dependencies": {
 "express": "^4.16.2",
 "mysql": "^2.15.0",
 "body-parser": "^1.18.2",
 }
 }

By typing following command you can install dependencies,

>>npm install

Initialization & Require

First will include require node modules and http server.
Also we have done connection of MySQL.

server.js

var app = require('express')(); // Express App include
var http = require('http').Server(app); // http server
var mysql = require('mysql'); // MySQL include
var bodyParser = require("body-parser"); // Body parser for fetch posted data
var connection = mysql.createConnection({ // MySQL Connection
 host : 'localhost',
 user : 'root',
 password : '',
 database : 'DbName',
 });
var app = express();
 
 connection.connect(function(err){
 if(!err) {
     console.log("Database is connected ... \n\n");  
 } else {
     console.log("Error connecting database ... \n\n");  
 }
 });
app.listen(3000);

Replace password value with MySQL root user password and DbName with database name you created earlier.

Now run the server with the following command

>>node server.js

If you get the log as Database is connected in terminal logs then your NodeJS setup with MySQL is complete.

Let’s see some GET and POST server requests with MySQL connection, so we take a book database as an example here.

GET

app.get('/book',function(req,res){
    var data = {
        "error":1,
        "Books":""
    };
    
    connection.query("SELECT * from book",function(err, rows, fields){
        if(rows.length != 0){
            data["error"] = 0;
            data["Books"] = rows;
            res.json(data);
        }else{
            data["Books"] = 'No books Found..';
            res.json(data);
        }
    });
});

here connection.query(“Query”,function)” will used for writing query and in callback will get required data as you can see above code.

POST

app.post('/book',function(req,res){
 var Bookname = req.body.bookname;
 var Authorname = req.body.authorname;
 var Price = req.body.price;
 var data = {
 "error":1,
 "Books":""
 };
 if(!!Bookname && !!Authorname && !!Price){
 connection.query("INSERT INTO book VALUES('',?,?,?)",[Bookname,Authorname,Price],function(err, rows, fields){
 if(!!err){
 data["Books"] = "Error Adding data";
 }else{
 data["error"] = 0;
 data["Books"] = "Book Added Successfully";
 }
 res.json(data);
 });
 }else{
 data["Books"] = "Please provide all required data (i.e : Bookname, Authorname, Price)";
 res.json(data);
 }
 });

And First will get posted data by using “req.body” to add book data to database using connection.query.
That will add book data and based on that return response as json.

 

Thanks.

How to Upload files on NodeJS Server Using Multer and Native File Transfer Plugin in Ionic 3

Welcome back guys, This post shows you How to Upload files on NodeJS Server Using Multer and Native File Transfer Plugin in Ionic 3. From our last post i was really excited to write a new post on working with NodeJS. As in the last post Integrating NodeJS server into an Ionic Application , we learned pretty much about NodeJS but now is the time for some serious action.
Uploading various format of files from the front end are pretty much useless without the API on the backend to receive them and save them, so here we are!
First things first lets talk about Multer.

Multer

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.
Multer works on the Express.
as from our previous post we discussed how to integrate ionic with NodeJS so moving further To easily setup file uploading in an Ionic application with Express.js server we can use Multer.js.

Native File Transfer Plugin

This plugin allows you to upload and download files.
This plugin defines global FileTransfer, FileUploadOptions constructors. Although in the global scope, they are not available until after the deviceready event.
The FileTransfer object provides a way to upload files using an HTTP multi-part POST or PUT request, and to download files.

Create an ionic 3 project and install File and File transfer plugin.

 $ ionic cordova plugin add cordova-plugin-media
 $ npm install --save @ionic-native/media
 $ ionic cordova plugin add cordova-plugin-file
 $ npm install --save @ionic-native/file
 $ ionic cordova plugin add cordova-plugin-file-transfer
 $ npm install --save @ionic-native/file-transfer

add this plugins to the app.module.ts and import the providers.

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Media, MediaObject } from '@ionic-native/media';

Creating Home.ts file for the setting up the upload options.
src/pages/home/home.ts

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
 import { File } from '@ionic-native/file';
 import { Media, MediaObject } from '@ionic-native/media';

Adding variable before constructors for holding audio

 recording: boolean = false;
 filePath: string;
 fileName: string;
 audio: MediaObject;
 audioList: any[] = [];

Add this function to get the audio

createAudio(){
 if (this.platform.is('android')) {
 this.fileName = 'record'+'-'+new Date().getFullYear()+'-'+new Date().getMonth()+'-'+new Date().getDate()+'-'+new Date().getHours()+'-'+new Date().getMinutes()+'.mp3';
 this.filePath = this.file.externalDataDirectory.replace(/file:\/\//g, '') + this.fileName;
 this.audio = this.media.create(this.filePath);
 }
 this.audio.startRecord();
 }
 audioFile(){
 this.audio.stopRecord();
 let data = { filename: this.fileName };
 this.audioList.push(data);
 this.upload();
 }

Add this function to upload the audio to the server

upload(){
 var name = "upload";

let option: FileUploadOptions = {
 fileKey:'file',
 mimeType:'audio/mp3',
 httpMethod:'POST',
 fileName:this.fileName
 };

const fileTransfer:FileTransferObject = this.transfer.create();
 console.log('filename = '+this.fileName);
 fileTransfer.upload(this.filePath, encodeURI('http://192.168.1.5:3000/upload'),option).then((result)=>
 {
 console.log("result = ", result)
 console.log('success');
 }).catch(error=>{
 // this.loader.dismiss();
 console.log('upload error');
 console.log(error);
 console.log("upload error source " + error.source);
 console.log("upload error target " + error.target);
 });
 }

Add android and run the application.

ionic cordova platform add android
ionic cordova run android

Now We Start by installing required node dependencies on server folder:

Installation:

npm init
npm install -S express multer body-parser cors path

the package.json file will look like this

server/package.json:

{
  "name": "app-name",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "multer": "^1.3.0",
  }
}

Now modifying server.js
server/server.js

var express = require("express");
 var bodyParser = require('body-parser');
 var cors = require('cors');
 var path = require('path');
 var multer = require('multer');

var app = express();
 app.use(bodyParser.json());
 app.use(cors());

Multer adds a body object and a file or files object to the request object.
Multer accepts an options object, the most basic of which is the dest property, which tells Multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk.

var upload = multer({ dest: 'uploads/' })

.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.

 var upload = multer({ storage: Storage }).single('file');
var Storage = multer.diskStorage({
 destination: function(req, file, callback) {
 var pathname = file.originalname.split('#');
 var path = pathname[0].replace('_','/');
 cb(null,'./uploads'+path);// null,upload_path
 },
 filename: function(req, file, callback) {
 var pathname = file.originalname.split('#');
 var filename = pathname[1];
 if(filename!=undefined)
 callback(null, filename);
 }
 });

In DiskStorage there are two options available, destination and filename. They are both functions that determine where the file should be stored.

destination is used to determine within which folder the uploaded files should be stored. This can also be given as a string (e.g. ‘/server/uploads’). If no destination is given, the operating system’s default directory for temporary files is used.

Now finally uploading the file to server.

app.post('/upload', multer({dest:'./uploads/'}).single('file'), function(req,res)
 {
 console.log("post result ==",res.json);
 console.log("post Req file == ",req.file)
 res.json('Audio uploaded');
 });

Note, that the dest parameter is relative to the server root folder, that is where the server.js is located.

Finally, start listening

var port = 3000;
app.listen( port, function(){ console.log('listening on port '+port); } );

Now run the server, go to terminal run

node server.js

or

npm start

Test it by uploading a file and find the uploaded file in the uploads folder. Multer will rename the file to a unique name to prevent collisions, so you will want to save the data from the req.files to your data store.

Integrating NodeJS server into an Ionic Application

What do you do if your application needs to pull in data from an external source, store data externally, share data with other users or needs to authenticate i.e. anything related to outside world? Answer is you will need to use any kind of back-end or server-side code. And for the same reason in this post, we are going to discuss about the integration of NodeJS server into an ionic application.

When your application is integrated with backend, the application will be communicating with the some server on the Internet that will acts as the go-between the application and any external service it needs to interact with(like a remote database).
There are many back-end services like Firebase, but as i like to prefer NodeJS is one of the most popular back-end when it comes to Ionic applications.The popularity of NodeJS as a back-end technology is at least partly due to the fact that it allows you to write your back-end with JavaScript as well which is overwhelming and comfortable for the developers as they don’t have to learn any new language to operate.

Prerequisite

NodeJS and Ionic should already be installed in your system. If you want to learn how to install ionic and NodeJS in your system just follow-up our previous post i.e. Full Ionic Framework Setup In Ubuntu Step-by-step tutorial.
This will help you in step-by-step guidance of installation of Ionic and NodeJS.
And now for some knowledge of ionic and NodeJS, I am going to spend a bit time explaining about ionic and node basics.

NodeJS

NodeJS is a server-side platform built on Google Chrome’s JavaScript Engine (V8 Engine). NodeJS is a JavaScript run-time which you can use on a server to run JavaScript code. This enables front end developers to create web services using JavaScript.
NodeJS eliminates the waiting, and simply continues with the next request. NodeJS also provides a rich library of various JavaScript modules which simplifies the development of web applications using NodeJS to a great extent.
NodeJS uses an event-driven, single-threaded, non-blocking I/O model that makes it light-weight and efficient, perfect for data-intensive real-time application that runs across distributed devices.

Project Structure

Ionic front-end and NodeJS backed are two separate entities so the management of project structure is important.
You should create two different folders inside a folder, one for NodeJS back-end code and another for ionic front-end code.

Create a folder named ion-node

create a folder inside ion-node called backEnd to hold your NodeJS server

generate a new ionic application insde ion-node called frontEnd

we are doing that because you should not put the server.js file in ionic project directory.

NodeJS server

To start a new NodeJS server you have to run only one command which will first of all create your package.json. Afterwards we install the needed npm packages.

:~/ion-node/backEnd$ npm init

While the npm creation runs you will get asked many questions. Most of them can be skipped by pressing enter using the default value, but make sure to set the entry point of your app to server.js. Of course you can change it later inside the package.json, but why not do it right in the first place here.

Your package.json file should now look like this:

 
 {
   "name": "my-app",
   "version": "1.0.0",
   "description": "demo server",
   "engines": {
   "node": "8.9.1"
   },
   "main": "server.js",
   "scripts": {
   "start": "node server.js"
 },
  "author": "",
  "license": "ISC",
  "dependencies": {
  "body-parser": "^1.18.2",
  "cors": "^2.8.4",
  "del": "^3.0.0",
  "express": "^4.16.2",
  "http": "0.0.0",
  "method-override": "^2.3.10",
  "morgan": "^1.9.0"
 }
 }

One important part of this package.json is that it defines the “start” script to be run. To start this server, the node server.js command must be run, because the file that contains our server code is called server.js. To run the server locally, you would first need to install any dependencies by running:

npm install

These are some attributes of Package.json:

  • Name − name of the package
  • Version − version of the package
  • Description − description of the package
  • Homepage − homepage of the package
  • Author − author of the package
  • Contributors − name of the contributors to the package
  • Dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package.
  • Repository − repository type and URL of the package
  • Main − entry point of the package
  • Keywords − keywords

now run the following command inside of the backEnd folder

npm install --save body-parser cors del express method-override morgan

now setting up the template for server.js

 var express = require('express');
 var bodyParser = require('body-parser');
 var logger = require('morgan');
 var methodOverride = require('method-override')
 var cors = require('cors');

var app = express();
 app.use(logger('dev'));
 app.use(bodyParser.json());
 app.use(methodOverride());
 app.use(cors());

app.post('/details',function(req, res){
 });

app.listen(process.env.PORT || 8081);

In the above code we are setting up the a few variables to hold reference to the various packages, we use require instead of import because we are using ES5 JavaScript here.

These packages are as follows:

  • Body-parser:  To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.
    Body-parser extract the entire body portion of an incoming request stream and exposes it on req.body. The middleware was a part of Express.js earlier but now you have to install it separately. This body-parser module parse the JSON, buffer, string and URL encoded data submitted using HTTP POST request.
  •  Method-override: The methodOverride() middleware is for requests from clients that only natively support simple verbs like GET and POST. So in those cases you could specify a special query field (or a hidden form field for example) that indicates the real verb to use instead of what was originally sent. That way your backend .put()/.delete()/.patch()/etc. routes don’t have to change and will still work and you can accept requests from all kinds of clients.
  • Morgan: Morgan is basically a logger, on any requests being made,it generates logs automatically. It outputs useful debugging messages.
  • CORS (Cross Origin Resource Sharing): CORS exists for security reasons and to limit which resources a browser can gain access to, from another website. If we try an AJAX/xmlhttprequest to a file like that, we get an error message from the console in our browser.
    The CORS rules apply to the same hostname and are also bound to the same port. If you only want to serve some routes to clients of all origins, you should set the res.headers specifically for these routes and omit the next(), but just send your response.
  • Express: Express is a minimal and flexible NodeJS web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. It allows to set up middlewares to respond to HTTP Requests. It defines a routing table which is used to perform different actions based on HTTP Method and URL.
    Here we created a new express application and then we setup our various packages on that application.

Now we can ask the server to start listening for request by calling the listen method. And whatever is a PORT environment variable defined it will start listening to request otherwise the server will start listening for request on port 8080 by default.

Now you just need to run the following command

node server.js

and the server would start running locally that means you could access it over

http://localhost:8081/

Creating Routes and Making Requests

we have created a working NodeJS server but the server only wouldn’t do anything with the requests yet so it doesn’t provide any responses.
The way that we would integrate NodeJS server into Ionic application is for Ionic Application to make HTTP requests to the server. Our Ionic application might make a request to:

 this.http.get('http://localhost:8081/details').map(res =>    res.json()).subscribe(data => {
   console.log(data);
 });

We are making a request to the /posts route and then we would expect that the server give us some useful information in the response. So, we need to set up these “routes” on our server that our application can make requests to, and we can do that using Express.
To set up a route in a NodeJS application that is using Express, all we need to do is this:

var express = require('express');
 var bodyParser = require('body-parser');
 var logger = require('morgan');
 var methodOverride = require('method-override')
 var cors = require('cors');

var app = express();
 app.use(logger('dev'));
 app.use(bodyParser.json());
 app.use(methodOverride());
 app.use(cors());

app.get('/details', function(req, res) {

console.log("details!");

});

app.listen(process.env.PORT || 8081);

If you wanted to handle a POST request instead of a GET request you would do this instead:

app.post('/details',function(req, res) {

res.json({"success":true});

});

we are going to create the requests that we want to send to our NodeJS server from our Ionic application. We will set up a form that allows us to enter a name, and some code to handle sending the results to the server.

Modify src/pages/home/home.html to reflect the following:

<ion-content padding>
 <ion-item *ngIf="isLoggedIn; else loginTemplate">
 <ion-item><h2>{{responseData}}</h2></ion-item>
 <button ion-button primary (click)="back()">Back</button>
 </ion-item>
 <ng-template #loginTemplate>
 <ion-item>
 <ion-label floating>Enter your name...</ion-label>
 <ion-input [(ngModel)]="name" type="text"></ion-input>
 </ion-item>
 <button ion-button primary (click)="Show()">Show</button>
 </ng-template>
</ion-content>

Modify src/pages/home/home.ts to reflect the following:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { map } from 'rxjs/operators';

@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
export class HomePage {
 userData: any;
 responseData;
 name: string;
 isLoggedIn:boolean = false;

constructor(private http: Http) {
 }
 back(){
  this.isLoggedIn = false;
  localStorage.clear();
 }

details() {
let data = {
 name: this.name
 };
 this.http.post('http://192.168.1.2:8081/details', data).pipe(
  map(res => res.json())
  ).subscribe(response => {
   console.log('POST Response:', response);
 });

 this.http.get('http://192.168.1.2:8081/details/' + this.name).pipe(
 map(res => res.json())
 ).subscribe(response => {
  console.log('GET Response:', response);
  this.responseData=response;
  window.localStorage.setItem('userData',JSON.stringify(response));
  this.isLoggedIn = true;
 });
 }
}

we are making two separate requests here. Once we click the ‘Show’ button We make a POST request to / details that will POST the data entered to the server. We also make a GET request that appends the data entered onto the end of the URL instead of POSTing the data. As you will see in a moment, we can actually set up multiple instances of the same route to handle different methods.

We are expecting to get a JSON response in return, and we log that out to the console.

Sending Response to Ionic

/ion-node/backEnd/server.js

var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var methodOverride = require('method-override')
var cors = require('cors');

var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cors());

app.post('/details', function(req, res){
 if(req.body.name.toLowerCase() === 'demo'){
 res.status(401).send({message: 'Sorry, no demo's!'});
 } else {
 res.send({
 passed: true,
 message: 'Welcome, friend!'
 });
 }
});

app.get('/details/:name', function(req, res){
 console.log("data called1");
 if(req.params.name.toLowerCase() === 'demo'){
 res.status(401).send({message: 'Sorry, no demo\'s!'});
 } else {
 res.json('Welcome'+' '+req.params.name);
 }
});

app.listen(process.env.PORT || 8081, function () {
 console.log('Example app listening on port 8081!');
});

In the code above, we have a route to handle our POST requests to /details and we also have a route to handle our GET requests to /details. In the POST route, we are able to access the data that is sent from our Ionic application through req.body.name. The GET route is a little different because we are supplying the data directly to the URL endpoint that is being hit. If we define a route that defines parameters using a colon like this:

 /details/:myvalue

and then we hit the following URL

http://localhost:8081/details/himasnhu

In both cases, we convert the supplied value to lowercase and see if it is equal to “demo”. If it is, we set the HTTP status to 401, which is the “Unauthorised” error code (you don’t have to do this, but it’s a good idea to provide useful status codes), and then in the POST route we send a response to the Ionic application by using the send method. If the name is not equal to “demo”, then we send a JSON object back that includes a message.
The GET route is very similar, except rather than using res.send we use res.json. These methods are mostly identical, and will both send a response back to the Ionic application, but the benefit of using res.json is that it will format any data supplied as valid JSON data (even if we just supply a simple string like ‘Welcome!’).

Our Ionic application and server should now be working as intended. If you run your server in the terminal using:

npm start

and you also run your Ionic application using another terminal instance.

WordPress Mobile App Development – Cost, Time, Technology, Functionality

Introduction:

This blog Post presents a detailed description of WordPress Mobile App Development – Cost, Time, Technology, Functionality.
All of the required features of the WordPress mobile App expressed by the client and all the features our development team is ready to provide is going to be expressed in this post.

 Scope:

The WordPress Mobile App is a website based android/ios application. This App helps you in easily converting News Website, or Magazine Website, or Blogs in to Smart Mobile Apps.

This app can be built with many native coding languages like if you want this application for android, you can use java, html, css and for iOS application you can use c, c++ & swift. but as for my choice I would choose Ionic Framework. The cutting edge latest technology of Ionic Framework and pulls in WordPress posts and other content using the WP-API plugin can be used as to build WordPress Mobile App.
Ionic is an open source front end SDK which can give a smart look, feel, and appearance for the Mobile App, along with an excellent UI interaction. Using Ionic, you can build beautiful hybrid Mobile App with HTML 5, CSS and JavaScript. The WP-API makes it easy to get WordPress content into our mobile app. To use it, you just have to install and activate the WP-API plugin on your WordPress site. After activating the plugin, you can see your API data by visiting an endpoint such as
http://yoursite.com/wp-json/wp/v2/posts.

WordPress Mobile App will also look at how to handle custom post types and other content using the same method we’ll use here. Once you know how to pull in posts, you can easily do the same for users, media, products, events, and lots more.

 WordPress Mobile App Requirements:

The application should have some functionality or features that are listed as below.

  • It should provide automatic content update on Home Page.
  • It should provide a search bar to filter the posts for user.
  • It should provide category wise Sorting of posts for user.
  • It should provide like or interested in post option for user.
  • It should provide sharing posts to social media platforms for user.
  • It should provide push notifications on user’s screen when a new post is published user will get the push notifications.
  • It should provide one tap commenting on the post and reply on the comments.
  • It should be designed in such a way that it won’t take too much space and can be installed in any place.
  • The application should also have built-in multimedia plugin that can play following multimedia: video, sound and picture files as posts.

 WordPress Mobile App Functionality:

  • Recent WordPress posts.
    1. Aim: To display the recent Featured posts in home page
    2. Input: open the application/ go to homepage.
    3. Output: Date wise sorted posts displaying on home page, recent post on the top.
    4. Process: Getting posts with the help of WP-API and Displaying it on home page.

 

  • View blog post/ “Read more” button:
    1. Aim: To View full blog post when tapped on it.
    2. Input: Tapping particular post to open on home page.
    3. Output: single post will open in a new page to display its full content with media.
    4. Process: when post/read more is tapped it will call a new page with its full content including media files with WP-API.

  • Categories and Tags:
    1. Aim: To display posts sorted by categories and tags.
    2. Input : selecting category option from the side menu.
    3. Output: displaying the sorted posts according to the category and the tags.
    4. Process : Sorting posts on the basis of categories and posts.

  • Search posts by query:
    1. Aim: To Display post on the basis of search query.
    2. Input: Inserting Query in the search bar on home Page.
    3. Output: Posts displayed filtered by search query.
    4. Process: search function works on all posts to filter the correct or related posts according to the query.

  • Comments:
    1. Aim: show and add comments on a particular post.
    2. Input: tapping the comment option on bottom of post.
    3. Output: comment added and displayed all the comments of a particular post.
    4. Process: comments are added and displayed with JSON API custom field.

  • Infinite scroll :
    1. Aim: scrolling posts shouldn’t stop until last post.
    2. Input: slide upside when the loader displayed.
    3. Output: post scrolling will not stop until last post of WordPress website.
    4. Process: infinite scroll lets the loader displaying until bringing more posts.
  • Social sharing of posts:
    1. Aim: Able to share posts on social media sites.
    2. Input: Tap on the share icon below the post and select particular social media platform to share the post.
    3. Output: post is shared.
    4. Process: when social platform is selected than it uses user authentication after that the post is shared to its profile.

  • Like the post :
    1. Aim: able to like the post.
    2. Input: tap the like icon below the post on home page.
    3. Output: post is liked.
    4. Process: post’s id is stored which is liked and the user’s interest is also recorded for the type of posts.

  • Push Notifications:
    1. Aim: show notification on user’s screen whenever new post is published.
    2. Output: notification pops up and when tapped redirects to the particular full blog post.
    3. Process: whenever new post is published in WordPress the push notification pops up on user’s screen.

WordPress Mobile App Perspective:

  • The WordPress Mobile App requires a WordPress site with a WordPress version greater or equal to 4.7 and just some plugins to that site to fetch and display results.
  • You can think of it like a single page web application that can access WordPress content through an API. This is where the WP-API comes in.
  • The WP-API is a new feature that has been proposed for WordPress core. It is a JSON REST API for WordPress, which means it makes much of your content easy to use in external applications, such as a mobile app.
  • The WP-API also allows two-way communication, such as creating posts and approving comments from the mobile app.
  • As over 24% of the Internet uses WordPress, and many of those folks want a mobile app. It makes perfect sense to use content from WordPress in the app, so that when the website is updated, the app is updated.
  • Ionic framework is an open source front-end SDK for developing awesome hybrid mobile apps with HTML5, CSS and JavaScript.
  • Ionic is focused mainly on the look and feel, and UI interaction of your app. Cordova is a platform to build Native Mobile Applications using HTML5, CSS and JavaScript.
  • The app uses SASS, which basically is CSS with super powers. Each component has its dedicated sass files and partials well structured with independent variables which provides you with complete modularity, flexibility..

WordPress Mobile App Uses:

  • Blogs:
    No wonder Blogs are already a step ahead to reach the online space and make a market itself. Then there is a best of all plan for them here that is Convert their WordPress Blog into a Smart Mobile App and always be the first one to leave behind the old times. And take your analytics at a whole new level.
  • Magazine Websites:
    what do you think how awesome magazine readers may feel when they do not have to go to a shop to buy a magazine? How convenient would it be for them if they can read their favourite column in magazine, on their mobile device? Present this wonderful experience to the valued customers. Magazine Authors could Simply convert their Magazine Website into a WordPress Mobile App now and get their business going to top.
  • News Website:
    Reading news in conventional old way is so boring and most of us don’t really have the time to sit with a news paper in our hand. Can you imagine how wonderful would the customers feel if they are able to read their daily news while travelling in a metro train or walking down to their offices? Are agency’s customers their true assets? Then, they should give their customers the wonderful gift of access to your News Website through few touches on their handheld mobile device which is a lot convenient and easy.

WordPress Mobile App Benefits:

  • Remind your users about your content with your icon and brand on your user’s home screen
  • App Store and Google Play profiles to acquire new users through mobile app installs.
  • Push notifications help retain users and drive repeated visits to your mobile app.
  • Mobile app specific advertising solutions mean no ad blockers will prevent you from monetizing your work.
  • Native mobile apps offer an improved mobile experience, which leads to more time spent in your app, more traffic and ad impressions.
  • WordPress mobile app will offer easy, native social sharing straight to the user’s social apps, which helps your content spread organically.

The WordPress Mobile App will be constantly improved and enhanced for it’s better performance.

Thanks

Google Sign-In in ionic 3

Google Sign-In is one of the easy way of  registration or login for user without entering lots of details in sign-up and then in sign-in form,Google Sign-In let us jump many steps and gets our data to the home page once we get logged in.

This plugin allows you to authenticate and identify users with Google Sign-In on IOS and Android. Out of the box, you’ll get email, display name, given name, family name, profile picture URL, and user id. You can also configure it to get an id Token and serverAuthCode.

This plugin only wraps access to the Google Sign-In API. Further API access should be implemented per use-case, per developer.

  • Generating a new Ionic 3 application:

    Let’s start by creating a new Ionic 3 application with the following command:

    ionic start ionic-google-oauth blank 

    Once that has finished generating, you should make it your current working directory by running the following command:

    cd ionic-google-oauth 

    We are going to be implementing a very simple example for this application, so we are not going to require any additional pages or providers. In the following step, we will need to supply the Bundle ID of the application. By default, this will be some generic Ionic Framework Bundle ID like this:

    <widget id="com.mycompany.somecoolapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

    by editing your config.xml file. It’s important that you do this now, as it will be a hassle to change it over later.

  • Configuring Google Sign-In for Android

    To install the Google Plus native plugin, you need Google Plus client id. To get the client id, Go to the Google console.
    Then click create a new project and give it a name.

    Then click the Google+ API link under the Social APIs.

    Then click the Enable API to enable the Google Plus API and Create credentials to create the client id for Google Plus.
    Choose Android from the Drop down of where will you be calling the API from?. And click the user data radio button too. Then click the what credentials do i need? button to proceed further.

    Now it will ask you to generate the SHA1 code.


    Use the below command in your terminal to generate the SHA1 code. It requires Java and Android Studio. So please check your system before using the below command.

    keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

    #If in case it didn’t work out then follow these steps:

    [

    To get the fingerprint(SHA1 ) just follow the below instructions :

    Step 1 :

    Go to - C:\Program Files\Java\jdk1.7.0_25\bin

    Step 2 :

    Inside the bin folder there is a .exe file which is named as “jarsigner.exe”. Double click on the .exe file and run it.

    Step 3:

    open command prompt (press Windows Key + R then type “cmd” without quotations in the appearing dialogue box and then press Enter Key).

    then type the code sniff below :

    cd C:\Program Files\Java\jdk1.7.0_25\bin
     then again type on cmd :
    keytool -list -keystore "C:/Documents and Settings/Your Name/.android/debug.keystore"

    Step 4:

    Then it will ask for Keystore password now. The default password if “android” type and enter

    Now Your are Done. You will have a Key Like Below 🙂

    ]

    Copy the SHA1 code from the terminal and paste it here. And get the package name from config.xml or AndroidManifest.xml. Then click the create client id button.
    Then give a name for your product, which will be displayed while using the Google Plus login. Click continue to generate the client id.

    Now the client id is created.

  • Installing the Google Plus Plugin

    We are now ready to install the Cordova plugin required to perform authentication, but before you do that it is important that you first run this command:

    ionic cordova platform add ios
     ionic cordova platform add android

    Use the below code to install the Google Plus native plugin to your Ionic 3 project.

    ionic cordova plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid
     npm install --save @ionic-native/google-plus

    Replace the myreversedclientid with your actual client id.
    Now create a button in the home.html with a click event.

    <button ion-button (click)="googlelogin()">Google Login</button>

    Then import the Google Plus class to home.ts.

     import { GooglePlus } from '@ionic-native/google-plus';

    Now create a reference in the constructor using.

     constructor(private googlePlus: GooglePlus) { }

    Then create a function to call the Google Login.

     glogin()
    {
    this.googlePlus.login({})
    .then(res => {
    console.log(res);
    alert("success "+JSON.stringify(res));
    })
    .catch(err => {
    console.error(err);
    alert("error "+JSON.stringify(err));
    });
    }

    The above code calls the Google Plus Login and gives the information in the alert box.
    Below is the response data after the successful login.

    email
    userId
    displayName
    familyName
    givenName
    imageUrl
    

    That’s all. You are done. You can generate the APK using the below command

    ionic cordova platform add android
    ionic cordova run android

    Deploy the APK on your physical device to test it. You can not test this plugin using the Android Emulator. You need to test this on the actual device. If you run this on the emulator, the Google Plus plugin won’t work.

 

Thanks

Facebook Login in Ionic 3

Login is the basic part of mobile app almost all app have login functionality. Facebook Login makes easy registration or login for user.

In Facebook Login we will allow our user to login with his Facebook account, and after we are authenticated we make a request to grab some user information from his Facebook profile. We will have to create a new Facebook app and connect our Ionic app to that app, but you will see it takes us only a few minutes to get a result like below.

Setting up a Facebook App

  • Before we start with our Ionic app we need a Facebook app.
  • Go to the Facebook developer Page.
  • Register yourself as a developer in facebook by clicking the Register button. It will ask your mobile number to validate you and your account password to authorize.
  • Then click the Add a new app to create a new facebook application.

  • Once you created the application, it will show the app id. You can use this app id to install the facebook plugin. However, you have to add the platform to this application first.

 

  • Type in the following command in your Terminal, where APP_ID and APP_NAME are the values from the Facebook Developer portal.
ionic cordova plugin add codova-plugin-facebook4 --variable APP_ID="12312312" --variable APP_NAME="myApp"
 npm install --save @ionic-native/facebook
  • you’ll need to add the native platforms you’ll be using to your app in the Facebook Developer portal under your app’s Settings and click “ADD Platform”:

  • Now you’ll need to open your project’s config.xml file, found in the root directory of your project and Take note of the id for the next step:
<widget id="com.mycompany.testapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  • iOS install : under “Bundle ID”, add the id from your config.xml file:

  • Android Install : Under ‘Google Play Package Name’, add the id from your config.xml file:

  • Now we just need to make sure that our Facebook plugin is loaded by adding it to the src/app/app.moduel.ts and in Providers too.
import { Facebook } from '@ionic-native/facebook';” 
  • We are almost done. Inside our view we only display a button in the beginning to start our Facebook login, and once the user is logged in we display some more personal data below including the user image! Go to src/pages/home/home.html and add:
<button ion-button full (click)="login()">Login</button>

 <ion-card *ngIf="data">

 <ion-card-header>{{ data.username }}</ion-card-header>

 <img [src]="data.picture" />

 <ion-card-content>

 <p>Email: {{ data.email }}</p>

 <p>First Name: {{ data.first_name }}</p>

 </ion-card-content>

 </ion-card>
 <button ion-button full (click)="logout()">Logout!</button>

Once we got the login token we could e.g. login to Firebase with that token, or simply continue to make requests to the Facebook API!

Now go to src/pages/home/home.ts and add:

 login(){

 this.facebook.login(['email', 'public_profile'])

.then((response: FacebookLoginResponse)=> {

  console.log("res",response);

  this.navCtrl.push(HomePage); 

this.facebook.api('me?fields=id,name,email,

first_name,picture.width(720).height(720).as(picture_large)', [])

.then(profile => {

  this.userData = { email: profile['email'],

  first_name: profile['first_name'],

  picture: profile['picture_large']['data']['url'],

  username: profile['name'] }

  localStorage.setItem("data", JSON.stringify(this.userData));

  })

.catch(err => {

 console.log(err);

  }) 

 })

 }

Now we have to generate the access tokens in facebook. So for generating accessTokens of facebook you have to add these lines to the Home.ts page.

this.facebook.getAccessToken().then(res => {

 console.log("token", res);

 let token = localStorage.setItem("token", JSON.stringify(res));

 }).catch(err => {

 console.log(err);

 }) 

And by these you also save fb generated token to the localstorage.

  • We use “facebook.getLoginStatus” to get the status of the user which are determined in 3 types.
    • the user is logged into Facebook and has authenticated your application (connected)
    • the user is logged into Facebook but has not authenticated your application (not_authorized)
    • the user is either not logged into Facebook or explicitly logged out of your application so it doesn’t attempt to connect to Facebook and thus, we don’t know if they’ve authenticated your application or not (unknown)

Knowing which of these three states the user is in is one of the first things your application needs to know on page load.

Declare variables to check if the user logged in and holds user data before the constructor.

isLoggedIn: boolean = false;

 users: any;

Inject Facebook plugin in the constructor add Facebook Connect method to check if the user is logged in.

constructor(public navCtrl: NavController, private facebook: Facebook) {

 facebook.getLoginStatus()

 .then(res => {

 console.log(res.status);

 if (res.status === "connect") {

 this.isLoggedIn = true;

 } else {

 this.isLoggedIn = false;

 }

 })

 .catch(e => console.log(e));

 }
  • Now the last point which Is logout():
logout() {

 this.facebook.logout().then(res => {

 localStorage.clear();

 }).catch(err => {

 console.log(err);

 })

}

Here in the last we are getting out of the facebook app and oour app also and clearing the localstorage also.

 

Thanks

Full Ionic Framework Setup In Ubuntu Step-by-step tutorial

Ionic Framework is useful for building mobile apps like Android and iOS. This post will help you to install Node.js, Cordova and Ionic framework on your system in Ubuntu.

As Ionic Framework depends on cordova, you need to install it first. To install Cordova, make sure you have Node.js installed. Following step by step guide shows what to do to install ionic so that you can build your brand new ionic app right away. This post is intentionally made precise rather explaining much stuffs. Lets get going!

  • Install JDK 8:

sudo add-apt-repository ppa:webupd8team/java  sudo apt-get update  sudo apt-get install oracle-java8-installer  sudo apt-get install oracle-java8-set-default
  • Install Node.js:

If you don’t have cURL installed, then install it first:

If you want to install cURL from repositories, the cURL is in Ubuntu repositories.

To install or update nvm:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

or Wget:

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

then –

sudo apt-get install curl

Run the following set of commands to install curl 7.50.3 on Ubuntu 16.04 in Terminal.
The same procedure can be followed for Ubuntu 15.04, Ubuntu 14.04 and other Ubuntu Derivatives:

 wget http://curl.haxx.se/download/curl-7.50.3.tar.gz

 tar -xvf curl-7.50.3.tar.gz

 cd curl-7.50.3/

 ./configure
 make

sudo make install

Once installed We Can verify cURL using:

 curl –version
Node.js

Node.js is a free, open-source and cross-platform Javascript run-time environment to execute server-side Javascript code. It can be used to develop intensive and dynamic web applications such as video streaming sites and single-page applications. Here the first command will install some required packages on the system. The second command will add PPA for node.js to your system. sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js

Preliminary Step for Installing Node:

First, log in to your server as your non-root user. Before doing anything else, let’s update the package database:

sudo apt update && sudo apt upgrade -y

There are a few methods which can be used to install Node.js on Ubuntu. We shall look at two methods.

Method 1 : Installing Bundled Node.js for Ubuntu 

You will usually need npm as well, so to install Node.js and npm via Ubuntu default depositories, execute:

sudo apt install nodejs npm

Once the installation is completed, you may want to verify the version of Node.js installed:

:~ $ nodejs -v
 [secondary_label output] v9.2.1

You can also check the version of npm installed:

:~ $ npm -v  5.5.1

Method 2 : Installing Latest Node.js 9.x  on Ubuntu 

Instead of installing from Ubuntu default depositories, you may want to install the latest version of Node.js. To do that, you need to add the PPA (Personal Package Archive) maintained by NodeSource for Ubuntu.

curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -

After adding the PPA, you can proceed to install Node.js which also includes npm when you install using this method:

sudo apt install -y nodejs

After the installation is completed, you can verify the version of Node.js installed:

node -v
[secondary_label output]
 v9.3.0

You can also check the version of npm installed:

 npm -v 
[secondary_label output] 5.5.1

For Method 2, in order to allow some npm packages to work (like compiling code from source), you need to install the build-essential package:

sudo apt install build-essential

Method 3 : Installing Latest Node.js using NVM

If you require to install multiple, self-contained versions of Node.js, then you need to use the nvm (Node.js version manager) method. Using the nvm, you can install and select which Node.js version to use.

Firstly, we need to install some requisite packages from the Ubuntu repositories in order for nvm to work:

sudo apt install build-essential libssl-dev

Once completed, we want to download and execute the nvm installation script. The current version is <^>v0.33.2<^>, which you may want to substitute with the latest version by checking out their GitHub page.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash

The script will create and clone the nvm repository into ~/.nvm directory inside your home directory. It will also add source lines into your profile (either ~/.bashrc, ~/.bash_profile or ~/.profile).

After the nvm installation is completed, you need to log out from your Ubuntu and log in again in order for nvm to work properly.

Next, we want to find out what versions of Node.js are available for installation:

nvm ls-remote
[secondary_label output]. . .        v8.8.0        
v8.8.1          v8.9.0   (LTS: Carbon)         v8.9.1   (LTS: Carbon)
v8.9.2   (LTS: Carbon)
v8.9.3   (Latest LTS: Carbon)
v9.0.0
v9.1.0
v9.2.0
v9.2.1
->     v9.3.0

The latest version at the time of writing this tutorial is v9.3.0. You may see newer versions instead. To install Node.js v9.3.0, enter:

nvm install <^>9.3.0<^>

You may replace 9.3.0 with whichever version number you require. You can also repeat installing other versions as you wish.

By default, nvm will use the most recently installed version. If you want to switch to another version, for example 9.0.0, use the following command:

nvm use <^>9.0.0<^>

To check which versions have been installed, enter:

nvm ls

You can make any installation as the default version. For instance, if you want to make 9.0.0 as the default version:

nvm alias default <^>9.0.0<^>

You can also select the default version by executing:

nvm use default

We have seen three methods to install Node.js on your Ubuntu server. While Method 1 is the easiest, you may want to choose Method 2 if you want to get the latest version of Node.js. If you need to run multiple versions of Node.js, then you need to use Method 3 to install.

  •  Install Cordova:

    Now use the following command to install Cordova on your system using npm command. It will install all other required node modules on your system.

 sudo npm install -g cordova

If you are running a 64-bit version of Ubuntu, you’ll need to install the 32-bit libraries since Android is only 32-bit at the moment.

sudo apt-get install ia32-libs  

If you are on Ubuntu 13.04 or greater, `ia32-libs` has been removed. You can use the following packages instead:

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0  
  • Install Ionic Framework:

Ionic provides and commands line utility for creating packages, build and start applications. Use NPM command to install Ionic framework on your system.

sudo npm install -g ionic

After completing the installation of the Ionic framework, use following command to check installed version.

ionic -v

3.1.9
  • Create Your Project:

Now, its time to create a new cordova project:

ionic start <projectname> blank

If you get Error: Cannot find module ‘xmlbuilder’, follow this step:

* Remove nodejs
* Delete the /usr/lib/node_modules (/usr/local/lib/node_modules) folder
* Reinstall nodejs
* Clear the npm cache (npm cache clean)
* Reinstalling ionic

  • Run App with Browser:

Go to your project root and run:

ionic serve

This will run demo app on your browser. While app is running, you can use following commands to do specific tasks needed:

  #restart or r to restart the client app from the root

#goto or g and a url to have the app navigate to the given url

#consolelogs or c to enable/disable console log output

  #serverlogs or s to enable/disable server log output

  #quit or q to shutdown the server and exit

If you are ok with web view of your app, then you’re done. Above steps are all you needed. But if you want to test your app on emulator/real device, keep moving..

  • Install Android Studio/ Android SDK to work for Android:

Make sure you’ve Oracle JDK 8 installed in your system

Download and install android SDK from official site:

Go to the location where you set to download the file.

  1. Rigth click the file[.tgz] and select Extract
    Here
    .

  2. Now you can see that a file called android-sdk-linux appears as if the following.
  3. Enter the folder android-sdk-linux.

  4. Enter the folder tools and then copy the folder location.

  5. Press the keys CTRL + ALT + T to open a terminal and then use the following command. Where /home/ep/Downloads/android-sdk-linux/tools is the location I copied previously. You can just type cd and right click to past the location to the terminal.

cd
/home/ep/Downloads/android-sdk-linux/tools
./android

Now the Android
SDK Manager
will be run.

Installing Packages

Click
Install [Number] packages....Click Accept
License
and then click Install.

Wait for the installation process

Finally, this message will be shown.

 

Editing “.bashrc”

Press CTRL + ALT + T to open a new terminal and type : gedit
~/.bashrc

Now the following text will appear.

 

Add the following to the top of the entire text and then save it. (Do not close the file)

export PATH=${PATH}:~/android-sdk-linux/tools export PATH=${PATH}:~/android-sdk-linux/platform-tools

[Recommended] Move the whole file android-sdk-linux to your eclipse’s workspace and under a folder that you create named Android. Moreover, you have to copy the location.

Now back to the “.bashrc” file and the replace the ‘~’ with the location you copied previously and then save it and close it.

  • Logout and relogin into Ubuntu.

 

We have now completely installed ionic into our ubuntu system and set up every essential configurations.

 

Thanks

 

 

Infinite Scroll in Ionic 3 applications

Infinite scroll is a very useful tool, It is the popular replacement for pagination technique. As we know with the rise of social networks, the “feed” has become a popular design pattern, especially in mobile apps, which gives the idea of infinite scroll which is loading in new items (typically older items) to the bottom of a list as the user scrolls. It has same function as pagination for limiting displayed list of data on the view.

Infinite scroll is better used when getting data from a rest-api like WordPress.

This is what you are going to build!

 

Lets show some code for Infinite Scroll for WP-API (WordPress) posts in an Ionic 3 application.

Getting the WordPress posts onto html:

home.html

<ion-card *ngFor="let post of posts" >
  <ion-title text-wrap [innerHTML]="post.title.rendered" (click)="postTapped($event, post)">                </ion-title>
 <p text-wrap [innerHTML]="post.excerpt.rendered"></p>
 <a (click)="postTapped($event, post)"> Read more..</a>
 </ion-card>

Ionic directive we are going to use is the ion-infinite-scroll

<ion-infinite-scroll [enabled]="morePagesAvailable" (ionInfinite)="doInfinite($event)">

This <ion-infinite-scroll> should be below some kind of list.

Infitite Scrolling shown in Html.

home.html

<ion-infinite-scroll [enabled]="morePagesAvailable" (ionInfinite)="doInfinite($event)">
 <ion-infinite-scroll-content
 loadingSpinner="bubbles"
 loadingText="Loading more posts ...">
 </ion-infinite-scroll-content>
 </ion-infinite-scroll> 

we’re going to be making a call to the wordpress API to get some data to play with. To do this, we’ll create a .ts file that makes these API calls. This will have one provider which makes the main call through the URL and will be called when our app loads to get the initial data and the Infinite scroll will be called each time we need to load in new posts for the infinite scroll.

providers/wordpress.ts

import { Http, Headers } from '@angular/http';
import * as Config from '../../config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
.......
getRecentPosts(categoryId:number, page:number = 1){
 //if we want to query posts by category
 let category_url = categoryId? ("&categories=" + categoryId): "";
 return this.http.get(
 Config.WORDPRESS_REST_API_URL
 + 'posts?page=' + page
 + category_url)
 .map(res => res.json());
 }
 getCategory(category){
 return this.http.get(Config.WORDPRESS_REST_API_URL + "categories/" + category)
 .map(res => res.json());
 }
}

and finally the home.ts file

import { WordPressProvider } from '../../providers/wordpress/wordpress';
.......
export class HomePage {
 posts: Array<any> = new Array<any>();
 morePagesAvailable: boolean = true;
 constructor(...){}
ionViewWillEnter() {
 this.morePagesAvailable = true;
 this.WordpressProvider.getRecentPosts(this.categoryId)
 .subscribe(data => {
 for(let post of data){
 post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
 this.posts.push(post);
 }
 loading.dismiss();
 });
 }
 }
 getPosts(ev){
 this.ionViewWillEnter();
 var val =ev.target.value;
 if(val&& val.trim()!=''){
 this.posts = this.posts.filter((post) => {
 return (post.toLowerCase().indexOf(val.toLowerCase()) > -1);
 })
 }
 }

We still need to do one final thing. We need to let the ion-infinite-scroll know that we’re done loading in the new items. To do this, we need to broadcast the doInfite() event.

////from here the infite scroll starts

doInfinite(infiniteScroll) {
 let page = (Math.ceil(this.posts.length/10)) + 1;

//as wp-api shows 10 posts per page only
 let loading = true;

//calling provider for recent posts by category
 this.WordpressProvider.getRecentPosts(this.categoryId, page)
 .subscribe(data => {
 for(let post of data){
 if(!loading){
 infiniteScroll.complete();
 }
 post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
 this.posts.push(post); 
 loading = false;
 }
 }, err => {
 this.morePagesAvailable = false;//when the total blog posts are showed.
 })
 }

Infinite Scroll is described in this post deeply with the help of our previous post  i.e. Mobile Application using WordPress WP-API Ionic 3 where we used WP-API to get the post from WordPress blogs.

Problems Implementing College Application and its solutions

For our last post i.e. College Application in Ionic 3, we might get little difficulties during the implementation of the College Application so this is why we wrote this article that could be of your help.

Some of the main problems related to College application ad their respective solutions are shown below.

  • Sliding the images:

The sliding images on the home page is made to be possible with the <ion-slides> elements. Here we create templates to create slides and listen to slide events and the navigation between the slides are done by swiping or SlideTo() for specific slides  or SlideNext() the slide that follows the active slide.

///image slider script

 selectTab(index) {
 this.pageSlider.slideTo(index);
 }
 changeWillSlide($event) {
 this.tabs = $event._snapIndex.toString();
 }
  • Implementing Date:

It is used to present an interface to select date and times. In the project we have shown Events Page functioning with dates that all the event notification are sorted by the date. It is easy to use.

<ion-datetime displayFormat="MMMM DD, YYYY" min="2010" max="2025-10-31" [(ngModel)]="today"></ion-datetime>
  • Photo Gallery:

It need to display any kind of grid with pictures or photos to the user, It will display images in a gallery like infinite loop where we can always see the end of the previous image and the start of the following. Photo Gallery uses IonicImageViewerModule plugin, after that  create a very simple array inside our .ts file. And the html can be shows like this:

<ion-card>
  <ion-slides class="image-slider" loop="true" slidesPerView="2">
    <ion-slide *ngFor="let img of images">
      <img src="assets/imgs/{{img}}" class="thumb-img" imageViewer/>
    </ion-slide>
  </ion-slides>
</ion-card>

with the scss like:

 on-slide.swiper-slide{ 
   left: 25%; 
}
 .slide-zoom {
   background: #e6e6e6;
 }
 .thumb-img {
   padding:10px;
 }
  • Adding Google Map for Contact Info:

There are few steps for adding google map to an ionic2/ionic3 project.

    • Adding the Google Maps SDK to an Ionic Application : We can also embed google maps in mobile applications, we are using google map’s JavaScript API in here which provides the smartest approach to rendering markers, The JavaScript API on mobile is capable of handling maps with thousands of markers. include this JavaScript API in your index.html file and replace your api key which you can get from https://developers.google.com/maps/documentation/javascript/get-api-key
        • Add the JavaScript SDK:
          http://maps.google.com/maps/api/js?key=YOUR_API_KEY_HERE 

          include this JavaScript API in your index.html file and replace your api key which you can get from  Google API. 

        • Loading the Map:
          <ion-header>
           <ion-navbar>
            Maps
           </ion-navbar> 
          </ion-header> 
          <ion-content> 
          <ion-item id="map"></ion-item> 
            //by #map we can grab the reference with the viewChild later.
          <ion-content>
          
          

          Now we are going to modify the .ts file for getting the HTML references. 

          import { Component, ViewChild, ElementRef } from '@angular/core'; 
          declare var google;
          @Component({...})
          export class HomePage {
          @ViewChild('map') mapElement:
           ElementRef;
          map: any;
          constructor(...) {}
          ionViewDidLoad(){
          this.loadMap();
           }
          loadMap(){ //handles creating a new map and loding it to map div
          let latLng = new google.maps.LatLng(67.9290, -45.10);
          //letLng represent the location that we want to center the map on.
          let mapOptions = {
          center: latLng,
          zoom: 20,
          mapTypeId: google.maps.MapTypeId.ROADMAP
           }
          
          this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
           }
          
           }
          
        • And Finally some Style to show the map:
           scroll{ 
             height: 100%; 
          }
           #map {
           height: 100%;
            width: 100%;  
          }

          This post will help you overcome the difficulties during the implementation of College application in ionic 3.

 

 

Thanks