AppComponent中的RouteParams [英] RouteParams in AppComponent

查看:106
本文介绍了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);
    });
  }

这篇关于AppComponent中的RouteParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆