繁体   English   中英

如何在我的 Angular2 应用程序中列出/output @Routes 中的所有路由

[英]How to list / output all routes in @Routes in my Angular2 App

我有一个快速的问题。 我目前正在浏览https://angular.io/docs/ts/latest/api/router/Router-class.html但我想知道,在我的 Angular2 的main.ts中我的路线是这样定义的:

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/about-me', component: AboutMeComponent },
    { path: '/food', component: FoodComponent },
    { path: '/photos', component: PhotosComponent },
    { path: '/technology', component: TechnologyComponent },
    { path: '/blog', component:Blogomponent },
])

现在,在其他地方的组件中,我导入了路由器 class。在我的组件(或组件模板)中,我想遍历我定义的所有路由,或者只是能够访问它们。 有没有内置的方法来做到这一点? 就像某些返回 object 数组的 function 一样? 这是我想要的粗略想法......

@Component({
    selector: 'ms-navigation',
    templateUrl: 'src/navigation/navigation.template.html',
    directives: [ ROUTER_DIRECTIVES ]
})

export class NavigationComponent {
    constructor(private router:Router) {   
        // what can I do here to get an array of all my routes?
        console.log(router.routes); ????
    }
}

这是一个更好的版本,它将列出所有可能的路线(根据评论修复):

import { Router, Route } from "@angular/router";

constructor(private router: Router) { }

ngOnInit() {
  this.printpath('', this.router.config);
}

printpath(parent: String, config: Route[]) {
  for (let i = 0; i < config.length; i++) {
    const route = config[i];
    console.log(parent + '/' + route.path);
    if (route.children) {
      const currentPath = route.path ? parent + '/' + route.path : parent;
      this.printpath(currentPath, route.children);
    }
  }
}

显然有一种非常紧凑的方法来做到这一点:

constructor(private router: Router) {}

ngOnInit() {
  console.log('configured routes: ', this.router.config);
}

如果您只需要将路由路径作为字符串,您可以通过遍历Router对象的config数组来找到它们。

    for (var i = 0; i < this.router.config.length; i++) {
        var routePath:string = this.router.config[i].path;
        console.log(routePath);
    }

这是@Anand Rockzz答案的扩展。

是为 Angular 6.0 编写的,并列出了所有可能的路由,包括惰性路由( https://angular.io/guide/lazy-loading-ngmodules ):

更新

正如@Daniel B提到的:

[...] 这不再适用于 Angular 8.0

import { Route } from '@angular/router';
import { LoadedRouterConfig } from '@angular/router/src/config';

printPaths(parent: string, routes: Route[]) {
    const getFullPath = (path?: string) => {
        if (path) {
            return parent + '/' + path;
        }

        return parent;
    };

    for (let i = 0; i < routes.length; i++) {
        const route = routes[i];
        const fullPath = getFullPath(route.path);

        console.log(parent + '/' + route.path, route.component);

        if (route.children /*&& route.children.length > 0*/) {
            this.printPaths(fullPath, route.children);
        }

        if (route.loadChildren && route.loadChildren.length > 0) {
            var routerConfig = <LoadedRouterConfig>(<any>route)['_loadedConfig'];
            if (routerConfig) {
                this.printPaths(fullPath, routerConfig.routes);
            }
        }
    }
}

我正在使用这个comp。 以角度 9 获取所有路线

import { Compiler, Component, Injector, OnInit } from '@angular/core';
import { Route, Router } from '@angular/router';

@Component({
  templateUrl: './sitemap.component.html'
})
export class SiteMapComponent implements OnInit {

  public urls: string[] = [];
  constructor(private _router: Router, private compiler: Compiler, private injector: Injector) {

  }

  ngOnInit() {
    this._router.config.forEach(i => {
      this.getPaths(i);
    })
  }

  getPaths(route: Route, parent: string = '') {
    if (route.redirectTo) {
      return;
    }
    if (route.children) {
      route.children.forEach(i => {
        this.getPaths(i, parent + route.path);
      });
    }
    else if (route.loadChildren) {
      (<any>this._router).configLoader.load(this.injector, route).subscribe(i => {
        i.routes.forEach(j => {
          this.getPaths(j, parent + route.path)
        });
      });
    }
    else if (route.path != null) {
      this.setPath(route.path, parent);
    }
  }
  setPath(path, parent) {
    let fullPath: string;
    if (path != null) {
      if (parent) {
        fullPath = `/${parent}/${path}`;
      }
      else {
        fullPath = `/${path}`
      }
    }
    this.urls.push(fullPath)
  }
}

对于@angular 2.00 版,我能够通过 routeConfig 属性找到子项列表。

这是我的组件的示例。 请注意,我通过“父”属性访问子组件,因为组件实际上是子组件之一,因为我在子路由器插座中渲染它。

import { Component } from '@angular/core';
import {Route, ActivatedRoute, Router} from "@angular/router";

@Component({
    selector: 'list',
    template: require('./list.component.html')
})
export class ListComponent {
    children = new Array<RouteLink>();

    constructor(private router: Router, private activatedRoute: ActivatedRoute) {
        for (let child of activatedRoute.parent.routeConfig.children) {
            if (child.path && child.data["breadcrumb"]) {
                this.children.push(new RouteLink(child.path, child.data["breadcrumb"]));
            }
        }
    }
}

export class RouteLink {
    constructor(private path: string, private name: string) {  }
}

从 Angular 9+ 开始,您可以通过浏览器控制台查看一个注入了 Router 的组件:

window.ng.getComponent(document.querySelector('app-employee-overview')).router.config[0].children

如果您想通过导入组件来查看可用路由。

将您的路线分配给如下常量

const appRoutes: Routes = [
    {
        path: 'asd',
        component: asdComponent
    },
    {
        path: 'ar',
        component: arComponent
    }
];

export const routing = RouterModule.forRoot(appRoutes);

在这里您将能够导出路线

导入const 路由

import { routing }        from './app.routing';
export class AppComponent {
   route=routing;
   /// route.providers is an array which internally contains the list of routes provided
   console.log(route.providers);
}

这只是为了找到可用的路线。 不建议在此基础上实现逻辑

如果您有 Lazy 路由,则使用此解决方案会遇到问题。 我做了一个简单的bash命令来显示路由信息:

cd /path/to/app 
for r in $(find src -name "*.routes.ts"); do 
  echo $r; grep "path:\|component:\|loadChildren:" $r; 
done

我已经根据@OMANSAK回答创建了一个 util 函数。 使用 Angular 12 和延迟加载模块进行测试。

import { Injector } from '@angular/core';
import { Router, Route } from '@angular/router';

const routerUrls: string[] = [];

async function getPaths(router: Router, injector: Injector, route: Route, parent: string = ''): Promise<void> {
   if (route.redirectTo) {
       return;
   }
   if (route.children) {
       for (const childRoute of route.children) {
           await getPaths(router, injector, childRoute, parent + route.path);
       }
   } else if (route.loadChildren) {
       const lazyConfig = await router['configLoader'].load(injector, route).toPromise();
       for (const childRoute of lazyConfig.routes) {
           await getPaths(router, injector, childRoute, parent + route.path);
       }
   } else if (route.path !== null) {
       if (route.path !== '') {
           routerUrls.push(parent ? `/${parent}/${route.path}` : `/${route.path}`);
       } else {
           routerUrls.push(parent ? `/${parent}` : '');
       }
   }
}

/**
 * Returns routes of the app via the Angular Router.
 *
 * Important: The fallback route in the app module (path: "**")
 * has to be the last element in your top level app-routing-module.
 *
 * @param router Angular Router
 * @param injector Angular Injector
 * @returns Routes of the app
*/
export async function getAllPaths(router: Router, injector: Injector): Promise<string[]> {
   const topLevelRoutes = router.config.slice(
       0,
       router.config.findIndex((route) => route.path === '**') ?? router.config.length - 1
   );
   for (const i of topLevelRoutes) {
       await getPaths(router, injector, i);
   }
   return routerUrls;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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