获取Angular 2中路径的路径或名称

时间:2016-05-12 10:14:15

标签: angular router

我有两条路线,其中pathname不同,但component相同。有没有办法检查我导航前的路径是什么。到/add-username为前。 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');
   }

2 个答案:

答案 0 :(得分:2)

您要找的是:router.currentInstruction.component.routeName

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

答案 1 :(得分:2)

> = 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 get current route's alias