Angular2获取当前路线';s别名

Angular2获取当前路线';s别名,angular,angular2-routing,Angular,Angular2 Routing,我可以通过location.path()获得当前路线的路径,如:/about、/、/news。 但是,我如何获得它的别名(路由定义中的“as”部分) 有可能吗?看不到获取它的方法,但另一种方法是使用RoutedData传递路由别名 您不应该使用位置,而应该使用路由器实例 在组件中,使用以下命令将其注入构造函数: constructor(public router: Router) 然后,您可以通过以下方式获取组件的名称: this.router.currentInstruction.compo

我可以通过location.path()获得当前路线的路径,如:/about、/、/news。 但是,我如何获得它的别名(路由定义中的“as”部分)


有可能吗?

看不到获取它的方法,但另一种方法是使用RoutedData传递路由别名


您不应该使用位置,而应该使用路由器实例

在组件中,使用以下命令将其注入构造函数:

constructor(public router: Router)
然后,您可以通过以下方式获取组件的名称:

this.router.currentInstruction.component.routeName
我不知道如何从路由器配置中获得as。但RouterLink指令应该是正确的起点:

如果您知道可能的别名列表,则可以使用
router.generate
route.isActiveRoute的组合找出当前别名的名称:

例如,我有一个包含三个步骤的向导。我有一个数组中的步骤别名列表:

private wizardAliases = [
    'wizardStep1',
    'wizardStep2',
    'wizardStep3'
];
然后,我使用以下代码确定当前别名:

const alias = this.wizardAliases
    .map(alias => ({ alias, navigationInstruction: this.router.generate([alias]) }))
    .filter(x => this.router.isRouteActive(x.navigationInstruction))
    .map(x => x.alias);

if (alias.length === 1) {
    console.log(`alias is ${alias}`);
}

免责声明:我没有尝试查看这是否适用于路由参数。

注意:以下内容已通过2.0 beta系列测试。RC版本有一个更新的路由器组件,具有中断性更改。旧的已重命名为
路由器已弃用
。这尚未针对新路由器进行测试。

以下内容将根据您的活动路线打印
Foo
Bar

@组件({
选择器:“应用程序”,
templateUrl:'app/app.html',
指令:[路由器指令]
})
@线路图([
{路径:'/',名称:'Foo',组件:FooComponent,useAsDefault:true},
{路径:'/bar',名称:'bar',组件:BarComponent,useAsDefault:false},
])
导出类AppComponent实现OnInit{
构造函数(专用路由器:路由器){
}
恩戈尼尼特(){
console.log('当前路由名称',
这是._router.currentInstruction.component.routeName);
}
}

For>=Angular2 RC.x(新路由器)

新路由器中不再有别名

您可以获得本地组件的相对布线

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


为什么要获取别名?因为路径最终会本地化。我认为最好使用别名来检查我实际上在哪个页面上,但为什么不使用
location.path()
?如果您有哈希策略,location.path将不起作用。url/#/about将返回“/”而不是“about”路由器的最新迭代不包含
currentInstruction
什么等价物?当在子组件中时,您可以使用
this.\u router.root.currentInstruction.component.routeName
(注意root)-这取决于您想知道的根目录。另请参阅
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());
  });
}