我有以下结构的angular 4项目:
<form id='ui' onclick="out.value = txt.value;">
<output id='out' for='txt'></output>
<input id='txt' type='text'>
<button type='submit'>GO</button>
</form>
我的src
|- app
| |- home
| | |- home.component.ts/html/scss
| | |- home.module.ts
| | |- home.routing.ts
| | |- products
| | | |- products.component.ts/html/scss
|- app.component.ts/html/scss
|- app-routing.module.ts
|- app.module.ts
文件包含以下内容:
app.routing.module.ts
和const routes: Route[] = [
{
path: "home", component: HomeComponent, canActivate: [AppAuthGuard]
},
{
path: '', redirectTo: AppConstants.ROUTE_LOGIN, pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: false})],
exports: [RouterModule]
})
export class AppRoutingModule {
}
包含以下子项溃败:
home.routing.ts
在home.module.ts中,子溃败已使用{
path: "home",
component: HomeComponent,
children: [
{
path: '',
pathMatch: 'full',
component: HomeStatsComponent
},
{
path: 'products',
children: [
{
path: '',
pathMatch: 'full',
component: ProductsComponent
}
{
path: 'add',
component: AddProductComponent
}
]
},
]
}
导入。在home.component.html中有一个用于子路由的路由器出口。除默认子路由(RouterModule.forChild(HomeRoutes)
)以外的所有路由都可以成功运行(http://localhost:4200/home
可以正常运行)。 http://localhost:4200/home/products
不会给出任何错误,因为路由器出口为空,它仅显示空白。但是,如果我在http://localhost:4200/home
中定义了home组件的默认子路由,则可以正常工作。我做错了什么导致它无法正常工作?
答案 0 :(得分:1)
您可以尝试直接删除一级配置吗?由于您已经将其路由到home
,所以它正在/home
路由中找到/home
,因此根据配置,它变成了http://localhost:4200/home/home
[
{
path: '',
pathMatch: 'full',
component: HomeStatsComponent
},
{
path: 'products',
children: [
{
path: '',
pathMatch: 'full',
component: ProductsComponent
}
{
path: 'add',
component: AddProductComponent
}
]
}
]
答案 1 :(得分:1)
我通过延迟加载语法loadChildren
解决了该问题。并删除第一级配置。在此之前,我需要重新构建代码以导出本地路由模块,并将导入导入到本地模块。更改的文件如下:
home.routing.ts
:
const homeRoutes: Route[] = [
{
path: '',
pathMatch: 'full',
component: HomeStatsComponent
},
{
path: 'products',
children: [
{
path: '',
pathMatch: 'full',
component: ProductsComponent
}
{
path: 'add',
component: AddProductComponent
}
]
},
]
}
@NgModule({
imports: [
RouterModule.forChild(homeRoutes)
],
exports: [
RouterModule
]
})
export class HomeRoutingModule {}
然后app.routing.module.ts
:
const routes: Route[] = [
{
path: "home", component: HomeComponent, loadChildren: './home/home.module#HomeModule'
},
{
path: '', redirectTo: "login", pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: false})],
exports: [RouterModule]
})
export class AppRoutingModule {
}
然后在HomeRoutingModule
处导入home.module.ts
。