RouteParams in AppComponent

放肆的年华 提交于 2019-12-24 01:45:48

问题


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?


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



回答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 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



来源:https://stackoverflow.com/questions/37100244/routeparams-in-appcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!