首页 > 解决方案 > Angular Routes:多个插座,路径为字符串数组

问题描述

在我的 angular9 应用程序中配置了数百条路由路径,所以有没有办法使用具有单个字符串路径数组的多个出口。

当前代码:

const routes: Routes = [
    {
        path: 'Data/:EntityID/:Date',
        component: MyFormComponent,children:[
            {
                path: '',
                loadChildren: () => import('../data-entry/data-entry.module').then(m => m.DataEntryModule)
            }
        ], 
    } ,
    { 
        path: 'Settings/:EntityID/:Date',
        component: MyFormComponent,children:[
            {
                path: '',
                loadChildren: () => import('../data-entry/data-entry.module').then(m => m.DataEntryModule)
            }
        ]
    }
...
];
    
export const routing = RouterModule.forChild(routes);

那么有什么方法可以使用与字符串数组相同的路径。因为在上述方式的情况下,多个路径的相同组件的脚本正在增加。

const routes: Routes = [
    {
        path: ['Data/:EntityID/:Date','Settings/:EntityID/:Date',...],
        component: MyFormComponent,children:[
            {
                path: '',
                    loadChildren: () => import('../data-entry/data-entry.module').then(m => m.DataEntryModule)
            }
        ], 
    }
];
    
export const routing = RouterModule.forChild(routes);

请向我建议可能的方法。

谢谢。

标签: javascriptangular

解决方案


看一下Route界面:

interface Route {
  path?: string
  pathMatch?: string
  matcher?: UrlMatcher
  component?: Type<any>
  redirectTo?: string
  outlet?: string
  canActivate?: any[]
  canActivateChild?: any[]
  canDeactivate?: any[]
  canLoad?: any[]
  data?: Data
  resolve?: ResolveData
  children?: Routes
  loadChildren?: LoadChildren
  runGuardsAndResolvers?: RunGuardsAndResolvers
}

该路径被声明为字符串类型,因此您不能将其更改为字符串数组。如果这样做,您将收到此错误:

Type 'string[]' is not assignable to type 'string'.ts(2322)

相反,请尝试以下操作:

const routes: Routes = [
    {
        path: 'Data/:EntityID/:Date',
        component: MyFormComponent,`children`:[
            {
                path: '',
                loadChildren: () => import('../data-entry/data-entry.module').then(m => m.DataEntryModule)
            }
        ], 
    } ,
    { 
        path: 'Settings/:EntityID/:Date',
        redirectTo: 'Data/:EntityID/:Date', pathMatch: 'full'
    }
...
];

这样,您至少不会重复组件和子部分。


推荐阅读