Подтвердить что ты не робот

Как перечислить/вывести все маршруты в @Routes в моем приложении Angular2

У меня есть быстрый вопрос. Я в настоящее время просматриваю 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 },
])

Теперь в компоненте в другом месте я импортирую класс 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); ????
    }
}
4b9b3361

Ответ 1

Вот лучшая версия, в которой будут перечислены все возможные маршруты (исправлено в соответствии с комментариями):

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

Ответ 2

По-видимому, существует очень компактный способ:

constructor(private router: Router) {}

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

Ответ 3

Если вам нужны только пути маршрута в виде строк, их можно найти, итерации по массиву Router object config.

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

Ответ 4

Это расширение как ответ @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);
            }
        }
    }
}

Ответ 5

Для @angular версии 2.00 Мне удалось найти список детей через свойство routeConfig.

Вот пример моего компонента. Обратите внимание, что я получаю доступ к дочерним элементам через свойство parent, поскольку компонент на самом деле является одним из дочерних элементов, поскольку я передаю его в дочерний роутер-выход.

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

Ответ 6

если вы хотите посмотреть доступный маршрут, импортировав его в компонент.

назначьте свои маршруты константе, как показано ниже

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

это просто найти доступные маршруты. не рекомендуется применять логику на основе этого

Ответ 7

Вы сталкиваетесь с проблемами, используя это решение, если у вас есть Ленивые маршруты. Я сделал простую команду bash, чтобы показать информацию о маршрутизации:

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