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

Mik*_*Sav 44 typescript angular

我有一个快速的问题.我目前正在浏览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 },
])
Run Code Online (Sandbox Code Playgroud)

现在在其他地方的组件中我导入了Router类.在我的组件(或组件模板)中,我想遍历我定义的所有路由或只能访问它们.有没有内置的方法来做到这一点?像一些返回对象数组的函数?这是我想要的粗略想法......

@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); ????
    }
}
Run Code Online (Sandbox Code Playgroud)

Ana*_*kzz 24

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

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 在 Angular5 中,我只得到了这个的顶级路由,因为孩子是未定义的。我如何获得所有可能的路线(包括儿童)而不是所有加载的路线? (2认同)

Zol*_*csi 17

显然有一种非常紧凑的方法:

constructor(private router: Router) {}

ngOnInit() {
  console.log('configured routes: ', this.router.config);
}
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于模块。如果您的应用程序中有多个模块,您将只能根据您正在执行上述命令的模块获取路由。 (5认同)
  • 使用延迟加载时不起作用 (4认同)

Jos*_*ion 11

如果您只需要将路径路径作为字符串,则可以通过迭代Router对象的config数组来找到它们.

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


Adr*_*aul 5

这是对@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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Angular 8 现在有哪些替代方案? (3认同)

OMA*_*SAK 5

我正在使用这个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)
  }
}
Run Code Online (Sandbox Code Playgroud)


Pri*_*ati -1

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

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

const appRoutes: Routes = [
    {
        path: 'asd',
        component: asdComponent
    },
    {
        path: 'ar',
        component: arComponent
    }
];
Run Code Online (Sandbox Code Playgroud)

导出常量路由 = RouterModule.forRoot(appRoutes);

在这里您将能够导出路线

导入常量路由

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);
}
Run Code Online (Sandbox Code Playgroud)

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