[英]Angular 8 lazy loading with child routes
我正在编写Angular 8应用,并且试图延迟加载一些模块。 但是,在页面加载时,出现此错误:
错误:组件ProfileComponent不是任何NgModule的一部分,或者该模块尚未导入到您的模块中。
具体来说,我希望在遇到路线并加载组件时加载模块。 问题在于该组件是模块的一部分。
这是定义组件的子模块的代码:
@NgModule({
imports: [],
declarations: [
...
ProfileComponent
],
exports: [
...
ProfileComponent
]
})
export class ProfileModule { }
这是父模块中试图动态加载子模块的路由定义:
const routes: Routes = [
{
path: 'projects/profile/:id', component: ProfileComponent,
loadChildren: () => {
return import('./profile/profile.module').then(m => m.ProfileModule);
},
children: [
{ path: 'list/:id', component: ListComponent, outlet: 'sidebar' },
{ path: 'risk/:id', component: RiskComponent, outlet: 'sidebar' },
...
]
}
有没有一种方法可以在导航时加载组件和模块? 我尝试将有问题的ProfileComponent移到父模块中,但是当我导航到页面时(与延迟加载相反),它希望所有其子组件都存在。 我可以创建一个不使用任何子组件的登录页面,在其中可以单击重定向到动态加载子模块的路由,但是我不想在应用程序中添加另一层单击。
为什么不在父模块中使用
const routes: Routes [{path:'projects/profile/:id', loadchildren: './profile/profile.module#ProfileModule']
然后在subModule中
const subRoutes: Routes .....
@NgModule({
imports: [RouterModule.forChild(subRoutes)]
exports: [RouterModule]
有关更多信息,您可以检查“ 角路由和导航” => Milestone 3:Heroes功能
希望这可以帮助 ;-)
您应用的结构:
├── parent.module.ts/
│ ├── profile.module.ts/
│ └──profile.component.ts/
如果我没有误解您的问题,则应在ProfileModule中声明另一组路由,如下所示:
ProfileModule (不是父模块)
const routes: Routes = [
{ path: '', component: ProfileComponent }, // /projects/profile/1
{ path: 'list/:id', component: ListComponent, outlet: 'sidebar' }, // /projects/profile/1/list/15
{ path: 'risk/:id', component: RiskComponent, outlet: 'sidebar' } ///projects/profile/1/risk/20
]
//and then import it into your parent module RouterModule
@NgModule({
declarations: [ProfileComponent],
imports: [ RouteModule.forChild(routes) ],
exports: [ RouterModule ]
})
ParentModule-删除ProfileComponent
const routes: Routes = [
{
path: 'projects/profile/:id', loadChildren: () => import('./profile/profile.module').then(m => m.ProfileModule)
}
]
由于不推荐使用字符串语法, 因此在Angular 8中使用import
关键字进行延迟加载是正确的,但是您可以通过删除return关键字来使其更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.