且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 为多个根路径重用相同的延迟加载模块

更新时间:2023-08-17 08:58:52

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

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