How to detect URL change in angular 2?

14,615

Solution 1

You can inject Location and subscribe to it

import { Location } from '@angular/common';

...

constructor(location:Location) {
  location.subscribe(val => console.log(val));
}

As Harry mentioned. This only notifies about popState events (the router or similar code changing the URL)

Solution 2

Inject Location and use the onUrlChange event listener:

import { Location } from '@angular/common';

constructor(private location: Location) {
  location.onUrlChange(url => console.log(url));
}

Solution 3

You can achieve to subscribe to router events from your root file like this

constructor(private router: Router,
          private aRouter: ActivatedRoute) {
this.router.events.pipe(filter(e => e instanceof NavigationEnd))
.subscribe((s: NavigationEnd) => {
  //write your logic here
   console.log(s);
});
}
Share:
14,615
Huy Pham
Author by

Huy Pham

Updated on July 20, 2022

Comments