简体   繁体   中英

Angular2 Router: Get Route for URL without navigating

I want to display/hide routerLink s 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?

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" .

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,'*******************');
       }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM