我只是在尝试新的 Angular 8,我正在更新一个旧的 Angular 6 项目。
为了启用延迟模块加载,我没有将所有路由放在项目根目录中的单个 app-routing.module.ts 中,而是将它们移动到具有相关模块的特定文件夹中。例如
user (folder)
-----> user.module.ts
-----> detail (folder)
-----> detail.component.ts
-----> detail.component.html
在 app-routing.module.ts 我懒加载路由:
{
path: 'user',
loadChildren: () => import('./user/user.module').then(m => m.UserModule)
}
在 user.module.ts 中,我将路由声明为:
const userRoutes = RouterModule.forChild([
{
path: '',
component: UserComponent,
canActivateChild: [AuthGuard],
children: [
{
path: 'detail',
component: UserDetailComponent
}
]
},
...
]);
现在的问题是: AuthGuard 可以激活孩子,它检查用户是否经过身份验证。用户身份验证在服务(AuthService)上,并且属性isAuthenticated是一个主题,所以每次我登录时我都会这样做
this.isAuthenticated.next(true)
反之亦然,当我注销时
this.isAuthenticated.next(false)
我第一次登录时,一切正常。如果我注销并再次登录,即使登录成功,我也会被重定向到登录页面。
事实上,如果在 Auth Guard 我订阅
this.authService.isAuthenticated.subscribe(console.log)
我第一次可以在控制台中看到登录时输出“true”,注销时输出“false”。当我再次尝试登录时,不会触发此订阅。
我怀疑这的罪魁祸首是用户模块的延迟加载。
不用说,在 Angular 6 上它是有效的。
谢谢!