You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15 Router:如何获取指定路由的子路由列表

在Angular 15中获取指定路由的子路由列表

方法1:从全局路由配置中查找静态子路由

如果目标路由是非懒加载的,可直接通过Router服务的config属性遍历匹配父路由,再提取其children属性:

import { Router } from '@angular/router';

@Component({ /* 组件配置 */ })
export class YourComponent {
  constructor(private router: Router) {}

  getTargetChildrenRoutes(parentRoutePath: string) {
    // 根据父路由path找到对应的配置项
    const parentRouteConfig = this.router.config.find(route => route.path === parentRoutePath);
    // 返回子路由列表,无则返回空数组
    return parentRouteConfig?.children ?? [];
  }
}

方法2:处理懒加载路由的子路由

如果父路由是懒加载(配置了loadChildren),直接从router.config拿不到子路由,需先加载对应模块再提取路由配置:

import { Router } from '@angular/router';

@Component({ /* 组件配置 */ })
export class YourComponent {
  constructor(private router: Router) {}

  async getLazyRouteChildren(parentRoutePath: string) {
    const parentRouteConfig = this.router.config.find(route => route.path === parentRoutePath);
    if (!parentRouteConfig?.loadChildren) return [];

    // 加载懒加载模块
    const loadedModule = await parentRouteConfig.loadChildren();
    // 适配不同模块导出方式,提取子路由配置
    const childRoutes = loadedModule.default?.routes || loadedModule.routes || [];
    return childRoutes;
  }
}

方法3:获取当前激活路由的子路由

若要获取当前已激活路由的子路由,可通过ActivatedRoute服务实现:

import { ActivatedRoute } from '@angular/router';

@Component({ /* 组件配置 */ })
export class YourComponent {
  constructor(private activatedRoute: ActivatedRoute) {}

  getActiveRouteChildren() {
    // 获取当前激活路由的静态子路由配置
    return this.activatedRoute.routeConfig?.children ?? [];

    // 若需获取已激活的子路由实例,可改用:
    // return this.activatedRoute.children;
  }
}

注意事项

  • router.config中的children是静态路由配置,ActivatedRoute.children是当前已激活的子路由实例,二者用途不同。
  • 懒加载路由的子路由必须在模块加载完成后才能获取,因此需用异步方法处理。

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:20:00