【问题标题】:canLoad not firing & module still loading?canLoad 未触发且模块仍在加载?
【发布时间】:2020-07-18 21:58:35
【问题描述】:

您好,我目前正在制作一个 Angular 应用程序,我有 2 个模块:一个 GuessModule 和一个 AdminModule;该模块中的一个应始终加载 GuessModule 并且另一个具有 canLoad 保护。

// app-routing.module.ts
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./modules/guest/guest.module').then(m => m.GuestModule),
  },
  {
    path: 'admin',
    loadChildren: () => import('./modules/admin/admin.module').then(m => m.AdminModule),
    canLoad: [
      AuthGuard
    ],
  },
  {
    path: '**',
    redirectTo: '/'
  }
];

// app.component.html
<router-outlet></router-outlet>

我有一个带有 AuthGuard 的 CoreModule:

/// CoreModule forRoot called in app.module imports CoreModule.forRoot()
static forRoot(): ModuleWithProviders {
   return {
      ngModule: CoreModule,
      providers: [
        AuthGuard
      ],
    } as ModuleWithProviders;
  }

在我的 Auth Guard 中,我有这个:

canLoad(
   route: Route,
   segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
   return false; // to test
}

但是当我走“/”路线时,我加载了我的 2 个模块,但只有 GuessModule 应该加载,我不知道为什么我都加载了; canLoad 没有被触发,但 AdminModule 被加载。

我错过了什么吗?

谢谢。

【问题讨论】:

  • 您如何确定模块已加载?可以在AdminModule的构造函数中添加console.log语句来验证吗?
  • 这很简单,我查看了我的网络,我看到一个名为 default~modules-admin-admin-module~modules-guest-guest-module.js 的 JS 文件正在下载,当我删除路由管理员时它不加载。当我将 console.log 放入 AdminModule 构造函数时,我在控制台中看不到它。

标签: angular typescript routing


【解决方案1】:

我在开发模式下运行时观察到同样的情况,你看到模块被加载,并且认为 canLoad 防护没有阻止模块被加载。但是,如果您使用命令 'ng build --prod' 进行生产构建并在浏览器中运行它,您应该会发现与您要保护的模块关联的块确实没有被加载。所以 canLoad 功能似乎只适用于生产,而不是开发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 2020-01-02
    • 2021-05-31
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多