Get the path or the name of the routes in Angular

2019-07-15 04:29发布

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

2条回答
叛逆
2楼-- · 2019-07-15 04:39

>= 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

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-15 04:50

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.

查看更多
登录 后发表回答