What is the easiest way to get the name of the current route in Angular?

I was looking for a good way to get the name of the current route. It was the easiest to find.

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

Is there a better way? Thank!

+18
source share
3 answers

Thanks to 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;
  }
});
+27
source

The easiest way to find the current path is to either use it directly

this.router.url

or you can check the current path every time the router changes, using its events, such as

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

where routeran instance is created here in a constructor like this

constructor(private router: Router){ ... }
+25
source
constructor(private route:ActivatedRoute) {
  console.log(route);
}

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

Source: https://habr.com/ru/post/1674624/


All Articles