Angular reuse same lazy load module for multiple root paths

ⅰ亾dé卋堺 提交于 2020-01-12 14:29:34

问题


I've splitted my app into two modules: one with main basic functionality and other with less-used features like account settings, faq pages and more.

What I'm trying to accomplish is to lazy load the second module for some root route paths, like /account or /settings without having to create many different modules. As far as I know Angular lazy load only works with one root route, and the routes configured in the lazy loaded module are set as children of that route.

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

回答1:


To create an instance of a component in a lazy loaded module without the router, this snippet could help:

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 
            })
    }
}


来源:https://stackoverflow.com/questions/49435458/angular-reuse-same-lazy-load-module-for-multiple-root-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!