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

Angular 13中如何获取当前激活路由的模块名与控制器名?

在Angular 13中获取当前激活路由的模块与组件(控制器)名称

获取当前激活组件(控制器)名称

要获取当前路由对应的组件名称,你可以通过ActivatedRoute遍历到最底层的激活路由节点,再读取组件类的name属性:

ngOnInit(): void {
  // 遍历到最内层的激活路由
  let currentRoute = this.activatedRoute;
  while (currentRoute.firstChild) {
    currentRoute = currentRoute.firstChild;
  }

  // 获取组件名称(即控制器名称)
  const componentName = currentRoute.component?.name;
  console.log('当前控制器名称:', componentName);
}

获取模块名称

Angular没有直接提供路由关联模块的内置API,推荐在路由配置时通过自定义data字段标记模块名称,再从ActivatedRoute中读取:

第一步:在路由配置中添加模块名称数据

// 示例路由配置(以某模块的路由文件为例)
const routes: Routes = [
  {
    path: 'user',
    component: UserComponent,
    data: { moduleName: 'UserModule' }, // 自定义模块名称标记
    children: [
      {
        path: 'profile',
        component: UserProfileComponent,
        data: { moduleName: 'UserModule' } // 子路由同步标记
      }
    ]
  }
];

第二步:从ActivatedRoute中读取模块名称

同样遍历到最底层路由,读取data中的模块名称:

ngOnInit(): void {
  let currentRoute = this.activatedRoute;
  while (currentRoute.firstChild) {
    currentRoute = currentRoute.firstChild;
  }

  // 获取模块名称
  const moduleName = currentRoute.snapshot.data['moduleName'];
  console.log('当前模块名称:', moduleName);
}

合并实现

可以将两个逻辑整合到一起:

ngOnInit(): void {
  let currentRoute = this.activatedRoute;
  // 遍历到最内层激活路由
  while (currentRoute.firstChild) {
    currentRoute = currentRoute.firstChild;
  }

  const componentName = currentRoute.component?.name;
  const moduleName = currentRoute.snapshot.data['moduleName'];

  console.log('当前模块名称:', moduleName);
  console.log('当前控制器名称:', componentName);
}

注意:如果是懒加载模块,同样可以在懒加载路由的data中添加moduleName字段,读取方式保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:35:31