Angular 2 - Router - Parent y Child Routes

Nov 9, 2015 8:00:00 AM / by daniel.comas

Si en anteriores artículos veíamos como realizar un sencillo routing, hoy aprovechando la ponéncia de Brian Ford del Angular Connect (2015) veremos como hacer child routes.

 

Una de las ponéncias más sorprendentes del último angular connect fué la de "Routing in Eleven Dimensions with Component Router"

 

 

Child Routes

 

La idea del siguiente ejercicio será el de tener:

 

/ -> /users

/users -> users list

/users/{id} -> about me

/users/{id}/images -> images

 

 

Para ello crearemos el componente padre:

@Component({
selector: 'app',
viewProviders: [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}]
})
@View({
template: `
<div>MAIN HEADER</div>
<div class="container">
<router-outlet style="margin-left: auto;margin-right: auto;"></router-outlet>
</div>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/users' },
{ path: '/users', as: 'Users', component: UsersComponent }, //users list
{ path: '/users/:id/...', as: 'User', component: UserComponent } //the most important are the last three points which will use the child component to do this route not the current.
])
export class App {
router: Router;
location: Location;
constructor(router:Router, location:Location) {
this.router = router;
this.location = location;

this.router.subscribe(location => console.log("location changed: " + location));
}
}

 

Crearemos el Component de Usuarios:

@Component({
template: `
Users
<ul class="list-group">
<li class="list-group-item"><a [router-link]="[ '/User', { id: 'danicomas' }, 'UserAboutMe' ]">danicomas</a></li>
<li class="list-group-item"><a [router-link]="[ '/User', { id: 'otheruser' }, 'UserAboutMe' ]">otheruser</a></li>
</ul>
`,
directives: [RouterLink]
})
export class UsersComponent {
constructor(routeParams:RouteParams) {
}
}

 

Creamos el componente de Usuario:

@Component({
template: `
<h1></h1>
<nav>
<ul class="nav nav-tabs">
<li><a [router-link]="[ '/User', { id: id }, 'UserAboutMe' ]">About Me</a></li>
<li><a [router-link]="[ '/User', { id: id }, 'UserImages' ]">Images</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', as: 'UserAboutMe', component: UserAboutMeComponent },
{ path: '/images', as: 'UserImages', component: UserImagesComponent }
])
export class UserComponent {
name: string;
id: number;
constructor(routeParams:RouteParams) {
//We will obtain the user id
this.id = routeParams.params.id;
}
}

 

Creamos los componentes de AboutMe e Images:

@Component({
})
@View({
template: `
module_151811850626664
`
})
export class UserImagesComponent {
name: string;
constructor() {
this.name = 'Images';
}
}

@Component({
})
@View({
template: `
module_151811850626664
`
})
export class UserAboutMeComponent {
name: string;
constructor() {
this.name = 'Default';
}
}

 

Acordaros de los imports:

import {Component, View, provide} from 'angular2/angular2';
import {RouterLink, RouterOutlet, Router, RouteParams, ROUTER_PROVIDERS, Location, RouteConfig, LocationStrategy, HashLocationStrategy} from 'angular2/router';

 

 

del html:

<!DOCTYPE html>
<html>

<head>
<title>Angular 2 - Typescript in runtime</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>

<script>
System.config({
//use typescript for compilation
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
//map tells the System loader where to look for things
map: {
app: "./src"
},
//packages defines our app package
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts'
}
}
});
</script>
<script src="https://code.angularjs.org/2.0.0-alpha.44/angular2.js"></script>
<script src="https://code.angularjs.org/2.0.0-alpha.44/router.dev.js"></script>
<script>
System.import('app')
.catch(console.error.bind(console));
</script>

</head>

<body>
<app>
loading...
</app>
</body>

</html>

 

y del main.ts

 

//main entry point
import {bootstrap} from 'angular2/angular2'
import {App} from './app' //It contains the previous code (imports, parent and childs)

bootstrap(App)
.catch(err => console.error(err));

IT WORKS

 

Para que veáis el resultado:

 

/ -> /users

 

 

/users -> users list

 

 

/users/{id} -> about me

 

/users/{id}/images -> images

 

 

 

Topics: Ingens Developments, Programación, router, TypeScript, Angular, AngularJS, Component, JavaScript

daniel.comas

Written by daniel.comas

Lists by Topic

see all
Servicios gestionados

Categorías

Ver todas