我有两个模块,每个模块的html内都有一个路由模块文件和一个路由器出口。 我想根据我所在的模块来加载组件。
我的文件树如下:
project
|-- module2
|-- -- profil
|-- -- - profil.component.html
|-- -- - profil.component.ts
|-- -- - profil.component.spec.ts
|-- -- - profil.component.css
|-- -- module2-routing.module.ts
|- module1-routing.module.ts
|- module1.module.ts
|- module1.component.ts
|- module1.component.spec.ts
|- module1.component.css
我有以下文件:
module1-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'module2', loadChildren: './module2/module2.module#Module2Module' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class Module1RoutingModule { }
module1.component.html
<router-outlet name="m1"></router-outlet>
module2-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfilComponent } from './profil/profil.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profil', component: ProfilComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class Module2RoutingModule { }
module2 / home.component.html
<div id="module2-home">
<app-header></app-header>
<router-outlet name='m2'></router-outlet>
</div>
我尝试在路由文件中使用插座选项(例如:{路径:'profil',组件:ProfilComponent,插座:'m2'}),但出现此错误:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'
答案 0 :(得分:1)
// appRouting-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent },
{
path: 'modules', component: ModulesComponent,
children: [
{ path: 'module1', component: Module1Component, children: Module1_ROUTE },
{ path: 'module2', component: Module2Component, children: Module2_ROUTE }
]
}
];
//export your child routes from your module1 and module2 routing.ts files
//example:
export const Module1_ROUTE: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
引用子路由documentation。这样可以解决您的问题。
答案 1 :(得分:0)
为避免歧义,请在路径的路径中使用模块名称,以确保没有两个路径具有相同的路径。希望这能解决您的问题。 Angular 2 Different modules same routing