Angular重用同一延迟加载模块以用于多个根路径 [英] Angular reuse same lazy load module for multiple root paths

查看:56
本文介绍了Angular重用同一延迟加载模块以用于多个根路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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',
 },

推荐答案

要在没有路由器的延迟加载模块中创建组件的实例,此代码段可以帮助您:

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

这篇关于Angular重用同一延迟加载模块以用于多个根路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆