Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect URL change in angular 2?

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.

like image 476
Huy Pham Avatar asked Oct 07 '16 01:10

Huy Pham


People also ask

Which of the following will help you to detect a route change in Angular?

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.

What is NavigationEnd in Angular?

NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.

What is ActivatedRouteSnapshot in Angular?

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.


2 Answers

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);
});
}
like image 194
Mohammed Aamier Avatar answered Sep 20 '22 18:09

Mohammed Aamier


Inject Location and use the onUrlChange event listener:

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

constructor(private location: Location) {
  location.onUrlChange(url => console.log(url));
}
like image 42
David Avatar answered Sep 17 '22 18:09

David