itsource

내 Angular2 App에서 @Routes의 모든 경로를 나열/출력하는 방법

mycopycode 2023. 8. 5. 10:08
반응형

내 Angular2 App에서 @Routes의 모든 경로를 나열/출력하는 방법

잠깐 질문이 있습니다.저는 현재 https://angular.io/docs/ts/latest/api/router/Router-class.html 을 보고 있지만, 제 Angular2's에서 궁금했습니다.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 },
])

이제 다른 구성요소에서 라우터 클래스를 가져옵니다.내 구성요소(또는 구성요소 템플릿)정의된 모든 경로를 반복하거나 경로에 액세스할 수 있습니다.이것을 할 수 있는 기본적인 방법이 있습니까?객체 배열을 반환하는 어떤 함수처럼?여기 제가 원하는 것에 대한 대략적인 생각이 있습니다...

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

나는 이 회사를 사용하여 각도 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)
  }
}

각도 14 업데이트: configLoader.load

(<any>this._router).configLoader.loadChildren

이것은 @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);
            }
        }
    }
}

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

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

Angular 9+에서 브라우저 콘솔을 통해 라우터가 주입된 구성 요소를 볼 수 있습니다.

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

Lazy 경로가 있는 경우 이 솔루션을 사용하면 문제가 발생합니다.라우팅 정보를 표시하기 위해 간단한 bash 명령을 만들었습니다.

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

Angular 14에 대한 위의 @Vasco의 답변에 대한 작은 업데이트.

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

let routerUrls: { path: string; component: any }[] = [];

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

/**
 * 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 getAllRoutes(
    router: Router,
    injector: Injector
): Promise<{ path: string; component: any }[]> {
    routerUrls = [];
    const topLevelRoutes = router.config.slice(
        0,
        router.config.findIndex((route) => route.path === '**') ?? router.config.length - 1
    );
    for (const i of topLevelRoutes) {
        await getRoutes(router, injector, i);
    }
    return routerUrls;
}

구성 요소로 가져와 사용 가능한 경로를 확인하려는 경우.

아래와 같은 상수에 경로를 지정합니다.

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

내보내기 const routing = RouterModule. for Root(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);
}

이용 가능한 경로를 찾기 위한 것입니다.이를 기반으로 논리를 구현하는 것은 권장되지 않습니다.

언급URL : https://stackoverflow.com/questions/37569936/how-to-list-output-all-routes-in-routes-in-my-angular2-app

반응형