How to Detect Route Changes in Angular

In a current project at work, we need to be able to tell what the current route is in an Angular app regardless of which component is currently active. The code below does the trick. It's probably better suited for ngOnInit() than the constructor, but this still illustrates how to do it. In this example, we're just logging the URL to the console (this was just sample code I gave to one of the developers):

export class AppComponent {
  constructor(private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      if(event instanceof NavigationEnd)
        console.log("CURRENT URL: ", event.url);
    });
  }
}

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader