Get the path or the name of the routes in Angular 2

我们两清 提交于 2019-12-12 20:28:22

问题


I have two routes with a different path and name but with the same component. Is there a way to check what the path is when I navigate for ex. to /add-userOR the name for ex. AddUser

Routeconfig

app.component.ts

@RouteConfig([
      {
        path: '/add-user',
        name: 'AddUser',
        component: UserComponent
      },
      {
        path: '/user/:id/detail',
        name: 'UserDetail',
        component: UserComponent
      }
    ])

Update

Usercomponent

user.component.ts

ngOnInit() {
//this is pseudocode
   if (this._router.name == 'AddUser') {
        console.log('you want to add a user')
   }
   else{
        console.log('you want to see the details of a user');
   }

回答1:


What you are looking for is: router.currentInstruction.component.routeName

Small disclaimer: The new new router introduced in Angular 2.0 RC does not support route names. You might want to avoid using it.




回答2:


>= Angular2 RC.0 <= RC.3

There are no aliases anymore in the new router.

You can get the relative route of the local component

  routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
    console.log(curr.stringifiedUrlSegments);
  }

or the full path using

constructor(private router:Router) {}

  routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
    console.log(this.router.serializeUrl(tree));
  }

or

constructor(router:Router, private location:Location) {
  router.changes.subscribe(() => {
    console.log(this.location.path());
  });
}

See also Angular2 get current route's alias



来源:https://stackoverflow.com/questions/37183874/get-the-path-or-the-name-of-the-routes-in-angular-2

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