AppComponent中的RouteParams
问题描述:
我正在尝试制作一个简单的组件应用程序来测试Angular2,但是我非常想访问我的应用程序组件中的RouteParams。
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,
])
所以基本上我想要实现的是让用户转到 http://website.com/?id=21 ,然后让该网站显示21。我是否需要一个单独的组件,然后让我的AppComponent提供到该组件的路由,或者有某种方式在应用程序组件中访问路由参数?
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?
答
这可能会做您想要的
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);
});
}