Basic Navigation: Ionic 2

Today lets learn basics of navigation / routing in Ionic 2. Ionic 2 and Angular 2 makes use of navigation stack for its navigation system. i.e., we can push and pop views to and from navigation stack.

Forward Navigation: We push page reference of the page we want to navigate to.
Backward Navigation: We execute pop operation on navigation stack to remove the current view or top view.

Once we push a page reference of the page we want to navigate to, a back button or back arrow symbol is automatically added to the navigation bar and whenever user clicks on it, the pop operation is executed for us automatically.

Basic Navigation or Routing: Ionic 2


[youtube https://www.youtube.com/watch?v=VC-drnHG8Gg]

YouTube Link: https://www.youtube.com/watch?v=VC-drnHG8Gg [Watch the Video In Full Screen.]



Generating Page using Ionic 2 CLI(Command Line Interface)

ionic g page Second

OR

ionic generate page Second

This command creates Second page for us – which will have a TypeScript page(class file or component), a template file and a sass file.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SecondPage } from '../second/second';
 
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {}
  nextPage(){
    this.navCtrl.push(SecondPage);
  }
}

Here we import the SecondPage page. Next define nextPage method. When nextPage method is invoked, we push reference to the page we want to navigate to, to the NavController reference.

Important: Also make sure to import Second page inside src/app/app.module.ts file and specify the page reference inside declarations and entryComponents section.

src/pages/home/home.html

 < button ion-button (click)="nextPage();">
   Next Page
 < /button>

Here we invoke nextPage method when user clicks on ‘Next Page’ button. This should take the user to the second page. And the user will be presented with a back button in the second page, so that he or she can navigate back to the home page or the first page again – which calls pop method on NavController reference automatically.

Set Root Page

this.navCtrl.setRoot(SecondPage);

using setRoot method, and passing the page reference of the page you want to set as root page, you can set the root page dynamically.

src/pages/second/second.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-second',
  templateUrl: 'second.html'
})
export class SecondPage {
  constructor(public navCtrl: NavController) {
    this.navCtrl.setRoot(SecondPage);
  }
}

Next Video Tutorial
In the next video tutorial we shall learn to pass data between pages while navigating.

Advanced Routing Using Express: Node.js

After learning basics of routing, lets look at some of the advances/complex routing techniques of Express.

routes node server request response technotip Basic Routing Using Express: Node.js

In this video tutorial, we shall teach you how to work with multiple params and also defining routes with regular expressions.

Two params in a Route: Express
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var companies = [
   {
      "name": "Apple",
      "product": "iPhone"
   },
   {
      "name": "Google",
      "product": "Nexus"
   },
   {
      "name": "Oracle",
      "product": "sql"
   },
   {
      "name": "Microsoft",
      "product": "Windows"
   }
 ];
 
app.get('/user/:from-:to', function(req, res){
    var from = parseInt(req.params.from, 10),
        to   = parseInt(req.params.to,   10);
 
  res.json( companies.slice(from, to+1) );
});

Here we have an array of objects – which in real-time application we get from a database ( Ex: MongoDB ). Now we define a route, and get two params in a single URL. By fetching and parsing those two params, we pass it to slice method of array and get array objects within the range/limit. Also note the use of response in json formatting while sending the data using response object.

Regular Expressions in Routes: Express
app.js

1
2
3
4
5
6
7
8
9
app.get(/\/user\/(\d*)\/?(edit)?/, function(req, res){
 
if(req.params[0])
 res.send("Viewing user id: "+req.params[0]); 
else if(req.params[1])
 res.send("editing user with an id "+req.params[0]);
else
 res.send("Enter User ID!!");
});

we enter our regular expression between two forward slashes. And to escape the forward slash present inside our regular expression, we make use of escape character i.e., a back slash. After /user/ we can have zero or more digits, after that an optional edit keyword followed by an optional trailing forward slash.

These routes match our pattern:
/user/
/user/userId/
/user/userId/edit
/user/userId/edit/

Depending on which URL the user is requesting, we could serve the purpose, using conditionals.

Advanced Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=jYqhlVYnr30]

YouTube Link: https://www.youtube.com/watch?v=jYqhlVYnr30 [Watch the Video In Full Screen.]



Note: In our example we are simply displaying the view and edit modes. But in real-time applications you could replace it with some database queries and make sure the operations makes proper sense.

Basic Routing Using Express: Node.js

Today let us learn a very important lesson in any web application development i.e., setting up the routes.

basic route using Express Node.js

Express is an excellent web framework for Node.js

Basic Routing with Express
app.js

1
2
3
app.get('/', function(req, res){
    res.send("Hello World!"); 
});

This would output Hello World when users access the index or home page.

Basic Routing with Express
app.js

1
2
3
app.get('/myPhone', function(req, res){
    res.send("Sony Xperia!"); 
});

This would output Sony Xperia! when users access the /myPhone route.

Dynamic Routing with Express
app.js

1
2
3
app.get('/user/:username', function(req, res){
    res.send(" "+req.params.username+"'s profile!"); 
});

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.
Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Middleware for public folder files
app.js

1
2
3
4
5
6
var express = require('express');
var path = require('path');
 
var app = express();
 
 app.use(express.static(path.join(__dirname, 'public')));

This would set the public directory.

Middleware for public folder files
app.js

1
2
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

If you want your custom routes to be checked before the public folder, then you could specify it using another middleware, i.e., app.router

Note that, the ordering of Middleware is significant.

Sending HTML in Routs: Express
app.js

1
2
3
4
5
6
7
8
9
10
app.get('/', function(req, res){
    var msg = [
               "<h1>I love Google..</h1>",
               "<p>Because they make awesome products",
               "<br />like my Nexus 7 Tablet",
               "which is so amazing!"
    ].join("\n");
    res.send(msg); 
});
</p>

This would out put with all HTML semantics on the browser.

Get, Post, Put, Delete Requests
Web browsers by default support only get and post requests. But we can override methods and make sure our Node.js application supports even the Put and Delete requests.

Post Request
HTML Form
index.html present in public directory

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<form action="/user" method="POST">
<label for="name">Name: </label>
 <input type="text" name="name"/>
 <input type="submit"/>
</form>
</body>
</html>

Here we have a form with post method and also take note of action field value.

POST Route
app.js

1
2
3
4
5
app.use(express.bodyParser());
 
app.post('/user', function(req, res){
    res.send("Submitted user's name is: "+req.body.name);  
});

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

We could similarly write code for PUT and DELETE requests.
PUT & DELETE Routes
app.js

1
2
3
4
5
6
7
8
9
10
app.use(express.bodyParser());
app.use(express.methodOverride());
 
app.put('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});
 
app.delete('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Basic Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=zHykHw9JlhE]

YouTube Link: https://www.youtube.com/watch?v=zHykHw9JlhE [Watch the Video In Full Screen.]



Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

External Route File
/routes/index.js

1
2
3
4
5
6
7
/*
 * GET home page.
 */ 
exports.index = function(req, res){
  res.send('Google Nexus 5 To Be Release Shortly ..');
};

exports is a global provided by node.js
index is a name given by us; it’s a property name and we assign a function to it.

Accessing External Route File
app.js

1
2
3
var routes = require('./routes');
 
app.get('/', routes.index);

This would output: Google Nexus 5 To Be Release Shortly ..

Adding Routes to Your Server: Node.js

With this video tutorial, lets learn about testing our code snippets using REPL, before implementing it into the actual node application. And then, we’ll show you how to add routes to your node server.

routes-node-server-request-response

In this tutorial, we create 5 routes to the server:
“/” to “Home Page”
“/about” to “About Us”
“/contact” to “Contact Us”
/”satish” redirected to “Home Page”
anything else to “Page Not Found”

Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
C:\>node
> var url = require("url");
undefined
> var myURL = "http://Technotip.org:3030/about";
undefined
> url
{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] }
> url.parse(myURL).hostname;
'technotip.org'
> url.parse(myURL).port;
'3030'
> url.parse(myURL).pathname;
'/about'
>

Here we test our code snippets on the command prompt, before implementing it into our actual application. Working with node url module on command prompt, we learnt to make use of parse() method of url object to fetch the hostname, port and the pathname of the actual URL. We are interested in pathname – we’ll be using it in our node application.

Related Read: Read Evaluate Print Loop (RELP): Node.js

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var url= require("url");
var http= require("http");
 
     http.createServer(function(req, res){
 
var pathname= url.parse(req.url).pathname;
 
if( pathname === '/' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Home Page");
}
else if( pathname === '/about' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About Us");
}
else if( pathname === '/contact')
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Contact Us");
}
else if( pathname === '/satish' )
{
res.writeHead(301, { "Location": "/" });
res.end("Home Page");
}
else
{
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page Not Found!!");
}
   }).listen("8080", "127.0.0.1");
 console.log("Server running ..");

Here we require url and http module. Using http object we create HTTP Server. Using url object we call parse method to parse and fetch the path from the user request URL.

Once we fetch the path, using conditional statements we display the corresponding message with appropriate response header information. We also illustrate 301 redirection

Adding Routes to Your Server: Node.js


[youtube https://www.youtube.com/watch?v=ejER-HVhDm8]

YouTube Link: https://www.youtube.com/watch?v=ejER-HVhDm8 [Watch the Video In Full Screen.]



Note: Make sure to turn on the server before trying to access the server!
execution code
command prompt

1
2
3
4
5
 
C:\>cd node
 
C:\node>node app.js
Server running ..

Navigate to the folder where you’ve your app.js file located, and run the server by executing the script using node command.