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);
});
}
Author by
Huy Pham
Updated on July 20, 2022Comments
-
Huy Pham almost 2 years
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.