Angular2 - retrieve current url

I just updated to Angular 2.0.0-rc5 and my listener for the current page url seems to have been deprecated.

Previously I could access it by subscribing to the following:

constructor(private router: Router){
  router.subscribe(url => {
    if (url.instruction.routeName === 'Home'){
      this.home = true;
    }else{
      this.home = false;
    }
  });
}

As I changed pages it would output what was stored in the 'name' field for each page of the router.

I have checked through the current version of Router and ActivatedRoute with no luck finding something I can subscribe to that will reveal that data, only params defined with the colon. For example the '15' in site.com/user/:15 when all I want is 'user'.

Router.url will return what I'm looking for but won't allow me to subscribe to that data to know when changes occur.

How do you access the current route's path name?

Answers:

Answer

Look for router.events and subscribe to that. The typical event will be NavigationEnd and this will give you the url information that you need.

router.events.subscribe(x => {
            if(x instanceof NavigationEnd) {
                console.log(x.url);
                console.log(x.urlAfterRedirects);
            }
        });

Note that there are other kind of events too, but the basic scenario uses NavigationEnd.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.