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.

2
  • 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. Commented Oct 7, 2016 at 1: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. Commented Oct 9, 2016 at 23:45

3 Answers 3

4

Inject Location and use the onUrlChange event listener:

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

constructor(private location: Location) {
  location.onUrlChange(url => console.log(url));
}
Sign up to request clarification or add additional context in comments.

Comments

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)

5 Comments

Thanks. So there isn't any built-in way to catch all URL change then. not like: $rootScope.$on('$stateChangeStart', () => {...}) in angular 1
Property 'subscribe' does not exist on type 'Location'.
That was changed AFAIR. BrowserLocation has it, but that was made private. developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/… should work or if you use the Angular router, it allows to subscribe to changes as well (see link in the question).
I was getting "Property subscribe does not exist.." because I missed the correct import: import {Location} from '@angular/common';
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);
});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.