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

回眸只為那壹抹淺笑 提交于 2019-12-20 17:33:03

问题


I was looking for a good way to get the current route's path name. This was the easiest I could find.

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

Is there a better way? Thanks!


回答1:


Thanks everyone for the answers. Here is what I found that I had to do.

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



回答2:


easiest way to find current path is either you directly use

this.router.url

or you can check current path on every router change using its events like this

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

where router here is instance created in constructor like this

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



回答3:


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

or

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


来源:https://stackoverflow.com/questions/43360625/what-is-the-easiest-way-to-get-current-route-path-name-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!