tt9
tt9

Reputation: 6069

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
          }
        },
    }
]

Upvotes: 5

Views: 688

Answers (1)

Eeks33
Eeks33

Reputation: 2315

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);
}

Upvotes: 4

Related Questions