簡體   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