首页 > 解决方案 > 如何使用在另一个模块中定义的路由

问题描述

尝试在现有系统中实现一个新模块(从我的另一个系统带来)。无法正确定义路线。例如,当前仪表板路由正在工作 - 我希望Mycomponent也将被路由。

MyComponent 是在 MyModule 模块中定义的,不像所有其他没有自己的模块的组件。当我单击该路由路径时:路径:'/ MyComponent ',标题:'我的组件',图标:'',类:''我得到了通常的:错误错误:未捕获(承诺):错误: 无法匹配任何路由。URL 段:“MyComponent”错误:无法匹配任何路由。URL 段:'MyComponent 假设这是我的文件树:

app\app.module.ts
app\app.routing.ts
app\dahshboard\dahshboard.component.ts

app\MyModule\MyModule-routing.module
app\MyModule\MyModule.module.ts
app\MyModule\MyComponent

这是 app.module.ts:

const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 }
];

@NgModule({
 imports: [
  CommonModule,
  BrowserModule,
  RouterModule.forRoot(routes,{
   useHash: true
 })
],...

这是 sidebar.component.ts:

declare interface RouteInfo {
path: string;
title: string;
icon: string;
class: string;
}

export const ROUTES: RouteInfo[] = [

{ path: '/MyComponent', title: 'My component',  icon: '', class: '' },
{ path: '/dashboard', title: 'Dashboard',  icon: 'dashboard', class: '' },
{ path: '/AAA', title: 'AAA',  icon:'AAA', class: '' },

这是 MyModule.module.ts

import { MyModuleRoutingModule } from './MyModule-routing.module';
@NgModule({
  declarations: [
    MyComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,      
    AppRoutingModule 
  ],
  providers: [],
  bootstrap: [AppComponent] 
})
export class MyModule { }

这是 MyModule-routing.module:

const routes: Routes = [
{ path: 'MyComponent',  component: MyComponent },
]
@NgModule({
  imports: [RouterModule.forRoot(routes) ],
  exports: [RouterModule]
})
export class MyModuleRoutingModule { }

标签: angularangular-routing

解决方案


您可以为 myModule 添加延迟加载,将您的 Routes 更改为:(如果您使用的是 angular ver 8 及更高版本,则检查文档会有所不同 https://angular.io/guide/lazy-loading-ngmodules

const routes: Routes =[
{
 path: '',
 redirectTo: 'dashboard',
 pathMatch: 'full',
}, {
 path: '',
 component: LayoutComponent,
 children: [{
   path: '',
   loadChildren: './layout.module#LayoutModule'
  }]
 },
 {
   path: 'MyComponent',
   loadChildren: './MyModule/mymodule.module#MyModule' 
 }

];

推荐阅读