Angular2 Router: Get the route for the URL without navigation.

I want to show / hide routerLink based on some Data from the router. The directive is implemented, but I miss the most important part ...

For example, I have the following router configuration (missing components):

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

Now I would like to ask Router for Route , which will be used if routerLink is /foo/bar or /baz/123 .

I searched for the source code of the Router ( https://github.com/angular/angular/blob/master/modules/%40angular/router/src/router.ts ) but could not find an easy way to do this. Especially how it handles these variables :id .

Of course, I could Router.config over Router.config , deeper and deeper. But then I will have to parse these variables, regular expressions, etc. There should be an easier way, because the angular router must internally do all this too.

Do you have an idea / solution?

+7
angular angular2-routing
source share
2 answers

The code you need is here: router / src / recognize.ts , but it is a private API that has a lot of private import, so it will be very difficult to make it work in your application.

Instead, you can run router.navigateByUrl , wait for the RouteRecognized event RouteRecognized and cancel the navigation (for example, using the custom Guard). RouteRecognized will have all the necessary information. Obviously, this is a bad decision.

There is another approach, you can create an additional structure (visible map), which should contain the path + data. For example, the structure has the 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
source share

If you need current route data, how can you do this to get it

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

All Articles