在Angular中,子路由默认是基于父级URL的。但是,如果你想让子路由在没有父级URL的情况下被调用,你可以使用空路径(empty path)作为父级路由的路径。
下面是一个包含代码示例的解决方法:
首先,定义一个父级路由,并将其路径设置为空字符串:
const routes: Routes = [
{ path: '', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
接下来,在父级组件(ParentComponent)的模板中,使用
来显示子路由:
Parent Component
在子路由组件(ChildComponent)中,你可以正常地定义路径和其他路由参数:
const routes: Routes = [
{ path: '', component: ChildComponent },
{ path: 'other', component: OtherComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ChildRoutingModule { }
现在,当你访问/child
路径时,父级组件(ParentComponent)会被加载,并且在
中显示子路由组件(ChildComponent)。同时,你也可以访问/child/other
路径来加载其他子路由组件(OtherComponent)。
请注意,当使用空路径作为父级路由的路径时,父级组件(ParentComponent)将始终被加载,无论你访问什么路径。因此,你可能需要在父级组件中添加一些逻辑来处理其他路径的重定向或显示错误信息。