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

What is the easiest way to get Current Route Path Name in Angular?

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

this.route.snapshot.firstChild.url[0].path

有没有更好的方法?谢谢!

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

constructor(private router:Router) {
  router.events.subscribe(...);
}

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

this.router.url

或者您可以使用这样的事件检查每个路由器更改的当前路径

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

其中 router 这里是在构造函数中创建的实例,如下所示

constructor(private router: Router){ ... }

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

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