【问题标题】:Angular Router use function to get routesAngular Router 使用函数获取路由
【发布时间】:2018-01-20 01:43:14
【问题描述】:

如何在路由配置中调用函数以在 Angular 5 中设置子路由? 代码示例:

export const homeRoutes: Routes = [
  {
    path: 'home',
    component: HomeContainer
    children: [
      getChildrenRoutes()
    ]
  }
]

@NgModule({
  imports: [
    RouterModule.forChild(homeRoutes),
  ],
  ...
})
export class HomeRoutingModule {}

函数getChildrenRoutes() 返回Route。在 JIT 模式下它运行良好,但如果我让 AoT 构建它会引发错误:

错误中的错误:静态解析符号值时遇到错误。不支持函数调用。考虑用对导出函数的引用替换函数或 lambda ...

【问题讨论】:

  • 不支持函数调用
  • 嗯.. 检查gist.github.com/chuckjaz/65dcc2fd5f4f5463e492ed0cb93bca60 并且它是真的。 @JBNizet 任何想法如何设置路由对象,在哪里调用函数?尝试在HomeRoutingModule 构造函数中使用router.resetConfig(homeRoutes),但使用这种方法我无法输入路线。
  • 请在问题中包含您的 getChildrenRoutes() 代码

标签: angular angular2-aot


【解决方案1】:

首先您必须在主模型 (NgModel) 上配置主路由。在一个单独的类(app.module.routing.ts)中,您必须使用子级实现主路由。它会更接近如下

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path:'login',
    component:LoginComponent
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardModule',
      },
      {
        path: 'auth',
        loadChildren: './auth/auth.module#AuthModule'
      },
      {
        path: 'masterdata',
        loadChildren: './masterdata/master.module#MasterModule'
      }
     
    ]
  },
];
@NgModule({
  imports: [ RouterModule.forRoot(routes)],  /*, { enableTracing: true }) */ 
  exports: [ RouterModule ],
  providers:[AuthGuard,OnlyLoggedInUsersGuard,GuardService]
})
export class AppRoutingModule {}

所以这条路线预计还有 3 个子模块 1.仪表板 2.认证 3.主数据

因此您可能需要为每个模块创建文件夹,并为每个模块创建一个主 NGModule 和路由模块。这是其中一个子模块

const routes: Routes = [
    {
        path:"",
        data:{
          title: "MasterData"
     },
        children:[
            {
                path:"apptypes",
                component:ApprovalTypesComponent,
                data:{
                    title:"Approval Types"
                },
                canActivate:[OnlyLoggedInUsersGuard,AuthGuard]
            }
        ]
    }
];

@NgModule({
    imports:[RouterModule.forChild(routes)],
    exports:[RouterModule]
})

export class MasterRoutings{}
loadChildren: './masterdata/master.module#MasterModule'

此行将加载 "./masterdata/master.module" 路径中的子模块 和模块需要导出类 MasterModule 所以 Angular 将加载该类中的所有路由并添加到主路由表中。

希望这会有所帮助 谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2017-07-16
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多