我是角色4的新开发者 . 在我的一个项目中,我使用延迟加载进行路由 . 延迟加载模块包含子组件 . 但是,路由到子组件总是失败并出现错误 .
Error: Cannot match any routes. URL Segment: 'home/addGroup'
如果我做错了,你能帮忙吗?我尝试了所有方法,但没有一个成功 .
以下是我的模块和路由 .
index.html的:
<app-root></app-root>
app.module:
import { routes } from './app.routes';
@NgModule({
declarations: [
AppComponent,
UserSignupComponent,
UserLoginComponent,
],
imports: [
BrowserModule,
routes,
HttpModule,
FormsModule
]
});
app.routes:
import { HomeModuleModule } from './home-module/home-module.module';
export const appRoutes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: UserLoginComponent },
{
path: 'home', loadChildren: './home-module/home-module.module#HomeModuleModule'
}
];
export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.component.html:
<router-outlet></router-outlet>
homemodule:
import { routes } from './home.routes';
@NgModule({
imports: [
CommonModule,
BrowserModule,
routes,
HttpModule,
FormsModule
],
declarations: [HomeComponent, AddGroupComponent, AddItemComponent],
providers: [httpserviceClass, sharedserviceClass],
})
home.routes:
export const router: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{
path: 'home', component: HomeComponent,
children: [
{ path: 'addItem/:groupName', component: AddItemComponent },
{ path: 'addGroup', component: AddGroupComponent },
]
}
];
export const routes: ModuleWithProviders = RouterModule.forChild(router);
home.component.html:
<nav class="navbar navbar-default noMargin">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Budget</a>
</div>
<ul class="nav navbar-nav">
<li> <a [routerLink]="['addGroup']"> addgroup </a> </li>
</ul>
</div>
</nav>
<div>
<router-outlet></router-outlet>
</div>
关键是,我可以从登录组件重定向到home-module的“home”组件
“this.router.navigate(['home']);”
但是,从home组件,我无法路由到addGroup组件
<a [routerLink]="['addGroup']"> addgroup </a>
我错过了什么吗?
1 回答
我发现了这个问题 . 我必须承认,在我发布问题时,我的理解是错误的 .
我必须在这里提几点 .
我使用app.routes中的路径"home"路由到homeModule .
在home.routes中,我正在加载"HomeComponent"作为默认值 . 因此路由到"HomeComponent"是成功的 .
如果我们敏锐地观察home.routes,
它包含一个单独的“家”路线 .
由于这个不同的"home"路由在“app.routes”中也包含相同的名称"home",这增加了很多混乱 .
我有两种方法可以纠正 .
1.首先,要释放混淆,请将home.route中的'home'路由更改为'welcome' .
至
然后,现在,修复实际的错误 .
应改为
这将在加载homeComponent时重定向到home / welcome . 当您单击addGroup时,它会重定向到"/addGroup" . 所以结果路径是"/home/welcome/addGroup"
在这种情况下,路由到addGroup时的结果路径只是“/ home / addGroup”