Angular2 Router: Get Route for URL without navigating

3.3k views Asked by At

I want to display/hide routerLinks based on some Data from the router. The directive is done, but I'm missing the most essential part...

For example I have the following router config (omitted components):

[
  { path: '', children: [
    { path: 'foo', children: [
      { path: 'bar', data: { requiredPermissions: ['a', 'b'] } }
    ]}
  ]},
  { path: 'baz', data: { requiredPermissions: ['c'] }, children: [
    { path: ':id' }
  ]}
]

Now I'd like to ask the Router for the Route that would be used if the routerLink is /foo/bar or /baz/123.

I looked though the Router source code ( https://github.com/angular/angular/blob/master/modules/%40angular/router/src/router.ts ), but couldn't find some easy way to do this. Especially how it handles these :id variables.

Of course I could iterate over Router.config, going deeper and deeper. But then I'd have to parse those variables, regular expressions, etc. There must be an easier way, because the angular router must internally do all this stuff, too.

Do you have any idea / solution?

2

There are 2 answers

0
kemsky On BEST ANSWER

You could fire router.navigateByUrl, wait for RouteRecognized event and cancel navigation (for example using custom Guard). RouteRecognized will have all necessary information. Obviously it is bad solution.

There is another approach, you could create additional structure (kinda map), that should contain path + data. For example structure has path struct.baz-route={url:'baz/:id', perm: ['c']}, then [routerLink]="struct.baz-route.url.replace(':id', x)", then *ngIf="struct.baz-url.perm.indexOf('c')>-1".

0
Vikash Dahiya On

hey if you want the data from current route than you can do like this to get that

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

export class Component {

   constructor(private route: ActivatedRoute){
          let pathroots = this.route.pathFromRoot;
          let pathurl = '';
          pathroots.forEach(path => {

              path.url.subscribe(url => {
                   url.forEach(e => {
                      pathurl += e + '/';
                   });
              });


         });
         console.log(pathurl,'*******************');
       }

 }