我正在将Angular 4应用程序转换为Angular6。但是,在进行与路由相关的更改时遇到了问题。
现在,当我运行我的应用程序时,将加载Home组件,但不会加载具有空路径的子组件ContentsComponent
。
我的应用程序中的路由定义如下:
app.routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'support', component: SupportComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
home.routing.module.ts
const routes: Routes = [
{
path: 'home', component: HomeComponent,
children: [
{ path: '', component: ContentsComponent }, //<-- This component is not loaded
{ path: '**', redirectTo: 'home' }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
home.module.ts
@NgModule({
imports: [
HomeRoutingModule
],
exports: [],
declarations: [ HomeComponent, ContentsComponent ],
providers: [],
})
export class HomeModule { }
app.module.ts
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
HomeModule
],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy }
]
})
export class AppModule { }
home.component.html
<router-outlet></router-outlet>
编辑:请注意,我不想在/home
网址部分之后显示任何内容。
答案 0 :(得分:0)
要在子组件中进行路由,您需要提及其名称。
将“ / home”替换为“ home”。
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'support', component: SupportComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在HomeRoutingModule中,您无需再次提及“家”。
仅按以下方式命名子组件。
const routes: Routes = [
{
path: '', component: HomeComponent,
children: [
{ path: 'content', component: ContentsComponent },
{ path: '**', redirectTo: 'content' }
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
和如果您不想在路由时更改路由路径,则有两种选择
this.router.navigate(['/home/content'], { skipLocationChange: true });
或
const routes: Routes = [
{
path: '', component: HomeComponent,
children: [
{ path: '', redirectTo: 'content' }
{ path: 'content', component: ContentsComponent },
{ path: '**', redirectTo: 'content' }
]
}
];
如有疑问,请问我。 谢谢。
答案 1 :(得分:0)
是因为相对路径。尝试以下方法应该可以。
children: [
{ path: '', redirectTo: '/home/content' },
{ path: 'content ', component: ContentsComponent },
{ path: '**', redirectTo: 'home' }
]