Skip to content Skip to sidebar Skip to footer

Routeparams In Appcomponent

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

Solution 1:

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);
    });
  }

Solution 2:

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 routepath: '/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();
}

privatesetUpEvents(): void {
    this.router.subscribe((value: any) => this.onNext(value));
}

privateonNext(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

Post a Comment for "Routeparams In Appcomponent"