Get the path or the name of the routes in Angular

2019-07-15 04:08发布

问题:

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