【发布时间】:2020-06-30 15:15:23
【问题描述】:
我有一个库项目,其中有一个模块和几个组件。在我的实际应用程序中,我想动态加载库模块并渲染组件。在开发模式下一切正常,但是当我以生产模式运行我的应用程序时,总是从工厂获取空的组件数组(使用 moduleFactory.componentFactories)。下面是我的代码。任何人都可以帮我解决这个问题。我正在使用 Angular 9.1.0。
import { Injectable, Type, Compiler, Injector, ComponentFactory, NgModuleFactory } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { ApptorCustomCompHostComponent } from '@apptor/corecomps';
@Injectable({
providedIn: 'root',
})
export class LazyLoaderService {
private modules: Map<string, any> = new Map();
private componentRegistry: any[] = [
{ type: "textbox", className: "ApptorCorecompsWrapperComponent", moduleName: "ApptorCorecompsModule" }
];
constructor(private compiler: Compiler, private injector: Injector) {
}
public async getComponentFactory(componentType: string): Promise<ComponentFactory<any>> {
let compInfo = this.componentRegistry.find(c => c.type === componentType);
if (compInfo) {
let factories = this.modules.get(compInfo.moduleName);
if (!factories) {
await this.loadModule(compInfo.moduleName);
factories = this.modules.get(compInfo.moduleName);
}
let componentFactory = factories.find(f => compInfo.className === f.componentType.name);
return componentFactory;
}
return null;
}
async loadModule(moduleName: string) {
switch (moduleName) {
case 'ApptorCorecompsModule':
this.loadModuleInternal(moduleName, await import('@apptor/corecomps').then(m => m[moduleName]));
break;
case 'lazy':
this.loadModuleInternal(moduleName, await import('@apptor/corecomps').then(m => m[moduleName]));
break;
}
}
private loadModuleInternal(moduleName: string, moduleType: Type<any>) {
const moduleFactory = this.compiler.compileModuleAndAllComponentsSync(moduleType);
const componentFactories = moduleFactory.componentFactories;
this.modules.set(moduleName, componentFactories);
console.log("module loaded is: ", moduleName);
}
}
【问题讨论】:
-
我已经按照这个教程来懒惰地和动态地加载路由。它现在很旧,但仍然有效indepth.dev/dynamically-loading-components-with-angular-cli。也可以参考官方 Angular 网站angular.io/guide/dynamic-component-loader。也许它会对你有所帮助。
标签: lazy-loading production-environment angular9