【问题标题】:Angular reuse same lazy load module for multiple root pathsAngular为多个根路径重用相同的延迟加载模块
【发布时间】:2018-09-01 07:00:44
【问题描述】:

我已将我的应用分为两个模块:一个具有主要的基本功能,另一个具有较少使用的功能,例如帐户设置、常见问题解答页面等。

我想要完成的是延迟加载某些根路由路径的第二个模块,例如/account/settings,而无需创建许多不同的模块。据我所知,Angular 延迟加载仅适用于一个根路由,并且在延迟加载模块中配置的路由被设置为该路由的子路由。

 {
        path: 'account',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },
 {
        path: 'settings',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },

【问题讨论】:

  • 你需要确保你的延迟加载模块的路由包含你正在调用的两个路径
  • 怎么样?你可以发布一个例子吗?因为使用此配置,延迟加载的模块只能“看到”一个空字符串,因为根路由器使用了 /account/settings
  • 您好,我也遇到了同样的问题,请问您解决了吗?
  • 如果不手动加载惰性模块并渲染适当的组件,您将无法在当前的 Angular 版本中执行此操作。希望这将通过 Angular Ivy 解决
  • @JavierMarín 你有没有看到他们说 Ivy 可以解决这个问题?

标签: angular angular-router


【解决方案1】:

要在没有路由器的延迟加载模块中创建组件实例,这个 sn-p 可能会有所帮助:

class LazyLoader {
    constructor(private _injector: Injector,
                private _moduleLoader: NgModuleFactoryLoader) {
    }

    public loadLazyModule() {
        this._moduleLoader.load('./modules/settings/settings.module#SettingsModule')
            .then((moduleFactory: NgModuleFactory<any>) => {
                const moduleRef = moduleFactory.create(this._injector);

                // Here you need a way to reference the class of the component you want to lazy load
                const componentType = (moduleFactory.moduleType as any).COMPONENT_CLASS;
                const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(componentType);
                const componentRef = container.createComponent(compFactory);

                // Instance of the lazy loaded component
                componentRef.instance 
            })
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多