10

Route change can be detected using the router.events stream. (How to detect a route change in Angular 2?).

But I am not sure how to detect browser URL change.

Community
  • 1
  • 1
Huy Pham
  • 163
  • 1
  • 1
  • 7
  • Browser URL change can only be caused by 2 factors: Route change inside Angular2 or user manually type in new URL. You can subscribe to the former. The latter will reload the whole application and detecting it makes no sense. – Harry Ninh Oct 07 '16 at 01:24
  • Thanks for your comment. The later case could also be coming from user clicking other external URL, or clicking on their browser's bookmarks bar. In my application, I need to catch this to present an Unsaved Changes confirmation dialog to user. – Huy Pham Oct 09 '16 at 23:45

3 Answers3

4

Inject Location and use the onUrlChange event listener:

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

constructor(private location: Location) {
  location.onUrlChange(url => console.log(url));
}
David
  • 2,101
  • 2
  • 32
  • 41
3

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)

mikkun
  • 731
  • 5
  • 7
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks. So there isn't any built-in way to catch all URL change then. not like: `$rootScope.$on('$stateChangeStart', () => {...})` in angular 1 – Huy Pham Oct 09 '16 at 23:41
  • 1
    please see here: https://stackoverflow.com/questions/33520043/how-to-detect-a-route-change-in-angular-2 – peter70 Aug 03 '17 at 12:11
  • 1
    `Property 'subscribe' does not exist on type 'Location'.` – Inigo Oct 28 '17 at 18:05
  • That was changed AFAIR. `BrowserLocation` has it, but that was made private. https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate should work or if you use the Angular router, it allows to subscribe to changes as well (see link in the question). – Günter Zöchbauer Oct 28 '17 at 18:10
  • I was getting "Property subscribe does not exist.." because I missed the correct import: `import {Location} from '@angular/common';` – Ena Nov 20 '18 at 15:59
2

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);
});
}