Search code examples
angularangular4-router

Angular 4, get route data without actually routing


Is there something in Angular 4 I can call, where I pass in either a string, or the array of route tokens and get back the static route data for that route?

For example:

const targetRoute = '/test/route'
const routeData = {{something}}.getRouteData(targetRoute)

// { routeDataValue: 'something' } etc...

The data I am looking for is the data defined in the Route Definitions

 const routes: Routes = [
    {
        path: 'test/route',
        data: { //This data object
          animation: {
            value: 'fetching-results'
          },
          progress: 100,
          sectionIdentifier: {
            background: 'results',
            backLinkUrl: null,
            backLinkText: null
          }
        },
    }
]

Solution

  • You can get all your routes and route configs (including the data property) from the Router like this:

    import { Router } from '@angular/router';
    
    ...
    
    constructor(
      private router: Router) {
    }
    
    ngOnInit() {
      // all routes
      console.log(this.router.config);
    
      // data of test/route
      console.log(this.router.config.find(route => route.path === 'test/route').data);
    }