简体   繁体   English

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

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

I have a quick question.我有一个快速的问题。 I'm currently looking through https://angular.io/docs/ts/latest/api/router/Router-class.html but I was wondering, in my Angular2's main.ts I have my routes defined thus:我目前正在浏览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 },
])

Now in a component elsewhere I import the Router class. In my component (or the component template) I would like to loop through all my routes defined or just be able to access them.现在,在其他地方的组件中,我导入了路由器 class。在我的组件(或组件模板)中,我想遍历我定义的所有路由,或者只是能够访问它们。 Is there a built in way to do this?有没有内置的方法来做到这一点? Like some function that returns an object array?就像某些返回 object 数组的 function 一样? Here is a crude idea of what I want...这是我想要的粗略想法......

@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); ????
    }
}

Here is a better version which will list all possible routes (fixed according to comments):这是一个更好的版本,它将列出所有可能的路线(根据评论修复):

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);
    }
  }
}

Apparently there is a very compact way to do it:显然有一种非常紧凑的方法来做到这一点:

constructor(private router: Router) {}

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

If you only need the route paths as strings, you can find them by iterating over your Router object's config array.如果您只需要将路由路径作为字符串,您可以通过遍历Router对象的config数组来找到它们。

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

This comes as an extension to @Anand Rockzz 's answer.这是@Anand Rockzz答案的扩展。

Was written for Angular 6.0 and list all possible routes including the lazy ones ( https://angular.io/guide/lazy-loading-ngmodules ):是为 Angular 6.0 编写的,并列出了所有可能的路由,包括惰性路由( https://angular.io/guide/lazy-loading-ngmodules ):

UPDATED更新

As @Daniel B mentioned:正如@Daniel B提到的:

[...] this no longer works with Angular 8.0 [...] 这不再适用于 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);
            }
        }
    }
}

I am using this comp.我正在使用这个comp。 to get all routes in angular 9以角度 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)
  }
}

For @angular version 2.00 I was able to find a list of the children through the routeConfig property.对于@angular 2.00 版,我能够通过 routeConfig 属性找到子项列表。

Here is an example of my component.这是我的组件的示例。 Note, I'm accessing the children via the 'parent' property as the component is actually one of the children as I'm rendering it in the child router-outlet.请注意,我通过“父”属性访问子组件,因为组件实际上是子组件之一,因为我在子路由器插座中渲染它。

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) {  }
}

From Angular 9+, you can look at a component that has a Router injected, via the browser console:从 Angular 9+ 开始,您可以通过浏览器控制台查看一个注入了 Router 的组件:

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

if you want to look at the available route by importing into a component.如果您想通过导入组件来查看可用路由。

assign your routes to a constant like below将您的路线分配给如下常量

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

export const routing = RouterModule.forRoot(appRoutes); export const routing = RouterModule.forRoot(appRoutes);

here you will be able to export the routes在这里您将能够导出路线

import the const routing导入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);
}

this is just to find the available routes.这只是为了找到可用的路线。 not recommendable to implement logic based on this不建议在此基础上实现逻辑

You run into issues using this solution if you have Lazy routes.如果您有 Lazy 路由,则使用此解决方案会遇到问题。 I made a simple bash command to show the routing information:我做了一个简单的bash命令来显示路由信息:

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

I've created a util function based on the answer of @OMANSAK .我已经根据@OMANSAK回答创建了一个 util 函数。 Tested with Angular 12 and lazy loaded modules.使用 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