Angular:按URL解析所有路径段配置

smn*_*brv 8 typescript angular2-router angular

给定URL,例如/path/path2/path3/123;sdf=df路由配置:

{ path: 'path', data: { g: 'h' }, children: [
  { path: 'path2', data: { c: 'd' }, children: [
    { path: 'something', component: TestpageComponent, data: { a: 'b' } },
    { path: 'path3/create', component: TestpageComponent, data: { b: 'c' } },
    { path: 'path3/:id', component: TestpageComponent, data: { b: 'c' } },
  ] }
] },
Run Code Online (Sandbox Code Playgroud)

我需要的是找到所有段的实际配置,以便获得data所有级别(url的每个段)上的所有参数的结果集.

我可以通过例如分割段中的URL

console.log(this.router.parseUrl(url));
Run Code Online (Sandbox Code Playgroud)

或者更确切地说

console.log(this.router.parseUrl(url).root.children['primary'].segments);
Run Code Online (Sandbox Code Playgroud)

将返回

[{"path":"path","parameters":{}},{"path":"path2","parameters":{}},{"path":"and","parameters":{}},{"path":"123","parameters":{"sdf":"df"}}]
Run Code Online (Sandbox Code Playgroud)

因此,将URL拆分为段不是问题.但是我需要为每个段获取配置.

我可以获得所有路线的实际配置

console.log(this.router.config);
Run Code Online (Sandbox Code Playgroud)

我可以用段经过配置树,并找出我需要的分支,但它可能会导致,例如同时解决烦恼:id针对create段.所以,我想使用路由器解析配置方式,如果内部路由器实现改变,我不需要改变我的.

示例:想象我有50%的URL受到某些保护(例如,只有登录用户可以去那里),而其他50%不受保护(为每个人显示).因此,在导航菜单级别(在...之外router-outlet)我只想显示与当前用户相关的链接,因此我需要知道哪些路由受到保护.警卫/数据/任何只是问题的特定情况.

请不要坚持这个例子,我正在寻找一种获取特定URL配置集的常用方法.

无论如何这可能吗?

smu*_*rfy 6

使用版本2.x,您可以使用recognize路由器内部使用的功能来匹配网址RouteStateSnapshot.

import { recognize } from '@angular/router/src/recognize';

recognize(null, this.router.config, this.router.parseUrl(url), url).subscribe(route => {
    var routeSnapshot = route.root.firstChild;

    // Go to all children to get actual route.
    // If you use routes with children you should have
    // the full tree here
    var childSnapshot = routeSnapshot.firstChild;
    while (childSnapshot != null) {
        childSnapshot = routeSnapshot.firstChild;
        if (childSnapshot != null) {
            routeSnapshot = childSnapshot;
        }
    }

    let routeData = routeSnapshot.data || {};

    // routeData['a']...
});
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这似乎不再适用于版本4.x. 对于版本4.x,我创建了一个拉取请求,以Router向显示识别功能的方法添加新方法.

https://github.com/angular/angular/issues/15826

另一方面说明.通过添加来处理promise((识别或新路由器方法)的错误也是有意义的 .catch((rej) => { // some code if it fails to resolve route }).可能会发生无法解析url-> routestatesnapshot的问题.要么因为url错误,要么使用异步路由,LoadChildren并且路由尚未加载.即使使用异步路由,面包屑也可以很好地使用它.如果您使用它来检查权限,例如通过指令,则需要注意是否使用异步路由.