Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 以角度获取当前路由路径名称的最简单方法是什么?_Angular_Angular Routing - Fatal编程技术网

Angular 以角度获取当前路由路径名称的最简单方法是什么?

Angular 以角度获取当前路由路径名称的最简单方法是什么?,angular,angular-routing,Angular,Angular Routing,我正在寻找一种获取当前路由路径名的好方法。这是我能找到的最简单的 this.route.snapshot.firstChild.url[0].path 有更好的办法吗?谢谢 constructor(private route:ActivatedRoute) { console.log(route); } 或 找到当前路径的最简单方法是直接使用 this.router.url 或者,您可以使用以下事件检查每个路由器更改上的当前路径 this.router.events.subscribe

我正在寻找一种获取当前路由路径名的好方法。这是我能找到的最简单的

this.route.snapshot.firstChild.url[0].path
有更好的办法吗?谢谢

constructor(private route:ActivatedRoute) {
  console.log(route);
}


找到当前路径的最简单方法是直接使用

this.router.url
或者,您可以使用以下事件检查每个路由器更改上的当前路径

this.router.events.subscribe((res) => { 
    console.log(this.router.url,"Current URL");
})
constructor(private router: Router){ ... }
其中
router
这里是在构造函数中创建的实例,如下所示

this.router.events.subscribe((res) => { 
    console.log(this.router.url,"Current URL");
})
constructor(private router: Router){ ... }

谢谢大家的回答。这是我发现我必须做的事情

router.events.subscribe((event: Event) => {
  console.log(event);
  if (event instanceof NavigationEnd ) {
    this.currentUrl = event.url;
  }
});

虽然这个代码片段可能是解决方案,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。如果没有导入,甚至没有通过构造函数获取路由器?不工作。我已经通过构造函数共享了提供路由器的代码。显然需要进口。不管怎样,为什么downvote@FeloVilchesOr更短:
router.events.subscribe((\u:NavigationEnd)=>this.currentUrl=\ux.url)它像魅力一样工作。别忘了从“@angular/router”导入{Event,NavigationStart,NavigationEnd,NavigationError};