Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current route in Angular 5

I'm using { provide: LocationStrategy, useClass: HashLocationStrategy }, in my app.module.ts. But when I give this.route.url it always contains / whether I'm in /home or /dashboard or /profile

I need to get the particular route value

constructor(public router:Router) {} alert(this.router.url);

like image 456
Krishna Avatar asked Jun 19 '18 05:06

Krishna


People also ask

How do I get current url in app component?

you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.

How do you find the route of data?

Step 1: Inject Router Firstly, we have to inject Router in the component which will listen for events. Step 2: Subscribe on events Then, we subscribe to Router events. Step 3: Handle type of event Router events stream fires all router events.

What is NavigationEnd in Angular?

NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.


2 Answers

Not sure if this applies to v5, but may help anyway

You can also subscribe to router event NavigationEnd, this seems to be the best way to always get the current url.

important notes:
- make sure you place this code in the contructor() of the app.component.ts file, in order to always get the last url value.


// file: src/app/app-component

  export class AppComponent {
  constructor(private router: Router) {

    // listen to events from Router
    this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd) {
        // event is an instance of NavigationEnd, get url!  
        const url = event.urlAfterRedirects;
        console.log('url is', url);
      }
    })

  }
}
like image 131
guillefd Avatar answered Sep 25 '22 20:09

guillefd


Your route instance should be from Router

constructor(
    private router: Router
  ) { }

this.router.url // this must contains your full router path
like image 43
Pardeep Jain Avatar answered Sep 23 '22 20:09

Pardeep Jain