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.
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.
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)
$rootScope.$on('$stateChangeStart', () => {...}) in angular 1Property 'subscribe' does not exist on type 'Location'.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).import {Location} from '@angular/common';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);
});
}