What are Routes?
Routes are way to access various parts of website using friendly urls. For example if you have a motorcycle store - it will be very convenient if you can navigate to details of page of awesome suzuki GSX1000
using url
like:
mybikestore.com/suzuki/GSX1000
(instead of using things like:
mybikestore.com?product=%20%dfgg;ereGSX1000%dfg
which you have no chance to remember)
This way the url pretty clear for users and makes much more sense for developers too.
cannot stop myself from putting here picture of GSX1000 2016
Routes in Angular2
Since when talking about angularjs2 we talking about single page application architecture there all the work done by javascript. The routes in angular (both 1. and 2) is the way to load different views (like different pages) of the website. The changes in url triggering javascript event and javascript responds by loading corresponding views, pretty cool isnt it?
Server
Speaking about single page application - the idea of single page app is that only one page should be served from the server - so it need to be specially configured.Here is configuration of nodejs express server which makes it to serve only index page no matter of what route was chosen.
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.get('/*', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(process.env.PORT || 3000, function () {
console.log('Example app listening on port 3000!');
});
Routes in angular2
To implement routes in angular2 'angular2/router' module must be included
import {ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
Also, in the code of main component must present route definitions part - a code which defines the routes and their urls:
@Routes([
{
path: '/',
component: DashboardComponent
},
{
path: '/reports',
component: ReportsComponent
}
])
Notice that in this example we have two views: "Dashboard" and "Reports"
View
Like in angular1 - if you want to load routed views in your application you must use the ROUTER DIRECTIVE in the view of the component
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, Router, Route, RouteConfig} from 'angular2/router';
...
@Component({
selector: 'app',
template: `
...
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
Here is running code: Hope you have fun reading...