I'm trying to make a simple one component app for testing out Angular2, but I am very stuck on accessing the RouteParams in my app component.
This is what I have so far:
@Component({
selector: 'app',
template: '<h1>ID: {{id}}</h1>',
directives: [ROUTER_DIRECTIVES],
providers: []
})
@RouteConfig([
{ path: '/', component: App }
])
class App {
private id: string
constructor(params: RouteParams) {
this.id = params.get('id')
}
}
bootstrap(App, [
ROUTER_PROVIDERS,
])
So basically what I want to achieve is for the user to go to http://website.com/?id=21 and then for the website to display 21. Do I need to have a separate component for that and then have my AppComponent provide a route to that component or is there any of way of accessing the route parameters in the app component?
This might do what you want
constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
router.changes.first().subscribe(() => {
let urlTree = this.routeSerializer.parse(location.path());
console.log('serializer', urlTree.children(urlTree.root)[0].segment);
// or to get the next segment of the path:
// console.log('serializer', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
});
}
Here is how to RouteConfig for a route parameters
{path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent},
Here is a code from configured app that has routes and route parameters
@Component({
selector: 'my-app',
template: `
<h1 class="title">Component Router</h1>
<a [routerLink]="['CrisisCenter']">Crisis Center</a>
<a [routerLink]="['Heroes']">Heroes</a>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ // Crisis Center child route
path: '/crisis-center/...',
name: 'CrisisCenter',
component: CrisisCenterComponent,
useAsDefault: true
},
{path: '/heroes', name: 'Heroes', component: HeroListComponent},
{path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent},
{path: '/disaster', name: 'Asteroid', redirectTo: ['CrisisCenter', 'CrisisDetail', {id:3}]}
])
export class AppComponent {
constructor(private router: Router) {
this.setUpEvents();
}
private setUpEvents(): void {
this.router.subscribe((value: any) => this.onNext(value));
}
private onNext(value: any): void {
//uncomment to get the stacktrace
//throw new Exception("");
console.log(value);
}
}
the plunker for the example
In the full view you can see how the route and routeparams change displaying new content: click here