【问题标题】:Angular 8 lazy loaded routes and guardsAngular 8 延迟加载的路由和守卫
【发布时间】:2019-06-18 22:37:09
【问题描述】:

我只是在尝试新的 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 上它工作了。

谢谢!

【问题讨论】:

  • 试试一个叫argury的工具来检查
  • @emotionlessbananas 感谢您的建议。我想你打算从 rangle.io 进行角度占卜吗?
  • 抱歉拼写错误,是的,我本来打算这样做
  • Google 自动更正 :) 感谢您的工具,我不知道。

标签: angular angular8


【解决方案1】:

我该死吧。

为了移动到lay模块加载,我遵循了这个指南

https://angular.io/guide/lazy-loading-ngmodules

但是最后我忘记导出RouterModule了。现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多