这就是我设法做你想做的事的方法。这个想法是,由于登录组件位于惰性模块中,由于在导航到某些路由时路由器会加载惰性模块,因此您需要在模式内部导航到加载惰性模块并显示登录名的路由零件。这可以使用命名的路由器插座来完成。我对命名路由器插座不是很有经验,所以可能有一些需要改进的地方,但它似乎有效。
因此,假设您有一个惰性模块 LoginModule,其中包含一个显示登录组件的空路径路由,下面是如何定义根模块的路由:
export const ROUTES: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'login',
loadChildren: './login/login.module#LoginModule'
},
{
path: 'modal-login',
component: ModalLoginShellComponent,
outlet: 'modal',
children: [
{
path: '',
loadChildren: './login/login.module#LoginModule'
}
]
}
];
home 组件将有一个链接,允许在 modal 中打开 ModalLoginComponent(如 ng-bootstrap 示例所示)。这个 ModalLoginComponent 模板看起来像这样:
<div class="modal-header">
<h4 class="modal-title">Hi there!</h4>
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<router-outlet name="modal"></router-outlet>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
</div>
重要的部分是
<router-outlet name="modal"></router-outlet>
它允许在模态框内导航到一个路由,尤其是一个会加载惰性模块的路由。
ModalLoginComponent 的代码将具有以下 ngOnInit(),它将触发导航:
ngOnInit() {
this.router.navigate([{outlets: {'modal': ['modal-login']}}]);
}
这将因此加载 ModalLoginShellComponent 及其在模态主体内的默认延迟加载子路由。 ModalLoginShellComponent 是一个愚蠢的组件,什么都不做,只是将其作为模板
<router-outlet></router-outlet>