繁体   English   中英

在Angular 2中获取路径或路线名称

[英]Get the path or the name of the routes in Angular 2

我有两个途径有不同的pathname ,但具有相同component 当我浏览ex时,是否有办法检查路径是什么。 /add-user或ex的name AddUser

Routeconfig

app.component.ts

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

更新

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

您正在寻找的是: router.currentInstruction.component.routeName

小免责声明:Angular 2.0 RC中引入的新的新路由器不支持路由名称。 您可能要避免使用它。

> = Angular2 RC.0 <= RC.3

新路由器中不再有别名。

您可以获取本地组件的相对路径

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

或使用的完整路径

constructor(private router:Router) {}

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

要么

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

另请参阅Angular2获取当前路线的别名

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM