【问题标题】:LazyLoading and config angular NgModuleLazyLoading 和配置角度 NgModule
【发布时间】:2023-03-31 16:42:01
【问题描述】:

我有一个模块“DevicePreview”,它有一些路由,可以从根目录和另一个模块“内容”内部显示。

当从根 DevicePreview 调用时,有可用的路由 /a、/b 和 /c,当从 Content 调用时,它有 /a、/b 和 /z。

现在我正在导出 2 个这样的路由数组(名称是伪造的):

export const DEVICE_ROOT_ROUTES: Routes = [
  {
    path: 'a',
    component: DeviceAComponent
  },  {
    path: 'b',
    component: DeviceBComponent
  },  {
    path: 'c',
    component: DeviceCComponent
  }
];

export const DEVICE_CONTENT_ROUTES: Routes = [
  {
    path: 'a',
    component: DeviceAComponent
  },  {
    path: 'b',
    component: DeviceBComponent
  },  {
    path: 'z',
    component: DeviceZComponent
  }
];

现在我想将其移至延迟加载模块。 AFAIK 延迟加载模块我必须这样做:

 {
    path: 'device',
    loadChildren: 'app/+device/device.module#DeviceModule'
  }

由于我不想在 root 中启用 Z 或在 Component 中启用 C 并且既不生成 2 个不同的模块,所以我正在考虑在通过 .forChild(options) 加载时配置 DeviceModule

延迟加载时如何调用 forChild?我也可以考虑其他方法。

谢谢!

【问题讨论】:

  • 我不确定我是否理解这个问题,但即使使用延迟加载,所有路由也会合并到由单个路由器实例管理的一组中。要回答您的问题,在进行延迟加载时使用 loadchildren 而不是 children。
  • 我在这里创建了一个动态表单(动态渲染组件):stackoverflow.com/questions/43143956/… 它可以帮助您对如何动态渲染组件有不同的看法
  • 这不是动态加载元素的问题,而是在 2 个不同的模块上重用整个路由器树并进行小的更改
  • github上有一个请愿书来处理它:github.com/angular/angular/issues/15304

标签: angular lazy-loading ng-modules


【解决方案1】:

我不确定我是否遵循您想要完成的任务,但是您听说过 AuthGuard 吗?例如,您可以使用 canActivate 来验证是否可以访问路由。

例如:

{ 
        path: 'device', 
        loadChildren: 'app/+device/device.module#DeviceModule', 
        canActivate: [AuthGuard] 
},

然后:

@Injectable()
export class AuthGuard implements CanActivate {

constructor() {}

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
 {
   //Your logic here to check if for example the module trying
   //to access the route is actually allowed to do that

 }
}

文档:https://angular.io/api/router/CanActivate

【讨论】:

  • 抱歉,我不在那个项目上了,所以我不能提供任何关于有用性的反馈。但我的问题不在于身份验证,我想在应用程序的 2 个不同部分使用相同的子树,一旦你已经登录
猜你喜欢
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 2020-09-03
  • 2018-08-26
  • 2017-10-13
  • 2020-12-27
相关资源
最近更新 更多