延迟加载嵌套模块和路由
问题描述:
我在延迟加载模块中路由时遇到问题。延迟加载嵌套模块和路由
这里是我的“根”的路线:
const routes: Routes = [
{path: '', redirectTo: 'admin', pathMatch: 'full' },
{path: 'admin', loadChildren: 'app/admin.module#AdminModule'}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class MainRoutingModule {}
所以我从我的应用程序期望,是空的路径重定向到/admin
- 这工作正常,模块被加载。
我有另外一个重定向:
const routes: Routes = [
{path: '', component: AdminComponent, children: [
{path: '', redirectTo: 'app', pathMatch: 'full' },
{path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
{path: 'login', component: LoginComponent}
]},
];
@NgModule({
imports: [
RouterModule.forChild(routes),
AppModule
],
exports: [
RouterModule
]
})
export class AdminRoutingModule {}
这里我有两个方案:
- 如果用户进行身份验证重定向到
app
- 因此整个路径是/admin/app
- 否则重定向到
login
- 所以整个路径应该是/admin/login
终于在管理应用程序的路由:
const routes: Routes = [
{ path: '', component: AppComponent, children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent},
]}
];
现在的问题开始。如果我将以url localhost:3000/admin/app/(*)
的身份进入我的身边,一切都按预期工作,AuthGuard会被调用,url可以,如果用户未经身份验证,他会重定向到登录页面。
但是!如果我将输入localhost:3000
应用程序将我重定向到localhost:3000/admin/home
(缺少app
)并且未调用AuthGuard。它看起来像Angular正在省略admin-routing.module
并直接转到最后一个。
是什么原因?我该如何解决这个问题?
答
在AdminModule中您可以在默认路由中添加canActivate。
const routes: Routes = [
{path: '', component: AdminComponent, children: [
{path: '', redirectTo: 'app', pathMatch: 'full' canActivate: [ AuthGuard ]},
{path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
{path: 'login', component: LoginComponent}
]},
];