Saturday, December 23, 2017

How do I know what route I am on in the SPA-style Angular 4 routing?

At the component you are using to drive a menu system or whatever where you need to react to this bit of data have this import:

import { Router } from '@angular/router';

 
 

That allows for something like what is seen below, and this trick works both with and without the hash-tag-in-the-route hack.

constructor(router: Router) {
   router.events.subscribe((event: any) => {
      console.log(event);
   });

 
 

event.url herein will have the current piece of the route with a leading slash. Whenever you change routes seven different events seem to get triggered but each has the .url hanging off of their objects in these scenarios. The seven events are:

  1. NavigationStart
  2. RoutesRecognized
  3. GuardsCheckStart
  4. GuardsCheckEnd
  5. ResolveStart
  6. ResolveEnd
  7. NavigationEnd

No comments:

Post a Comment