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.
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.
ActivatedRouteSnapshotlinkContains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.
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);
});
}
Inject Location
and use the onUrlChange
event listener:
import { Location } from '@angular/common';
constructor(private location: Location) {
location.onUrlChange(url => console.log(url));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With