2

我正在尝试制作一个简单的单组件应用程序来测试 Angular2,但我非常坚持访问我的应用程序组件中的 RouteParams。

这是我到目前为止所拥有的:

@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,
])

所以基本上我想要实现的是让用户访问http://website.com/?id=21然后让网站显示 21。我是否需要为此设置一个单独的组件然后拥有我的 AppComponent提供到该组件的路由,还是有任何方法可以访问应用程序组件中的路由参数?

4

2 回答 2

1

这可能会做你想要的

  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);
    });
  }
于 2016-05-14T19:16:46.163 回答
0

下面是如何为路由参数进行 RouteConfig

{path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent},

这是来自已配置应用程序的代码,其中包含路由和路由参数

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

}

该示例的 plunker

在完整视图中,您可以看到路由和路由参数如何更改以显示新内容: 单击此处

于 2016-05-08T13:53:00.223 回答