angular - 动态加载惰性模块组件
问题描述
我想动态加载组件,会加载 app.module 中的组件,但不会加载惰性模块中的组件。
我尝试使用此代码。
import {
Injectable,
ComponentFactoryResolver,
ComponentFactory,
} from '@angular/core';
import {
NgModule,
Component,
Directive,
Input,
ReflectiveInjector,
ViewContainerRef,
Compiler,
ModuleWithComponentFactories
} from '@angular/core';
import { AboutUsComponent } from "../pages/about-us/about-us.component";
@Injectable()
export class ExampleService {
rootViewContainer: ViewContainerRef;
subcompPath = "app/lab/lab.module#LabModule";
constructor(private factoryResolver: ComponentFactoryResolver, private
vcRef: ViewContainerRef, private compiler: Compiler) { }
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
reset(): void {
this.rootViewContainer.clear();
}
insertHappyComponent(): void {
this.insertComponent(AboutUsComponent);
}
insertSadComponent(): void {
this.insertComponent(AboutUsComponent);
}
insertComponent(componentType: any): void {
const factory = this.factoryResolver.resolveComponentFactory(componentType);
this.rootViewContainer.createComponent(factory);
}
loadSubcomponent(compname: string) {
let [modulePath, componentName] = this.subcompPath.split("#");
(<any>window).System.import(modulePath)
.then((module: any) => module["LabModule"]) // Or pass the module class name too
.then((type: any) => {
return this.compiler.compileModuleAndAllComponentsAsync(type)
})
.then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
const factory = moduleWithFactories.componentFactories.find(x => x.componentType.name === compname); // Crucial: componentType.name, not componentType!!
let componentRef = this.rootViewContainer.createComponent(factory as ComponentFactory<any>, 0);
});
}
}
它从主模块加载组件,而不是从惰性模块 LabModule 加载。
我找到了一些我应该加载和编译惰性模块并加载它们的组件的代码,但我不知道如何准确地做到这一点。
解决方案
推荐阅读
- c# - System.DirectoryServices.DirectorySearcher 缓存改进或 FindAll() 过滤
- angular - 登录后刷新头部组件
- python - 如何使用python脚本找出寄存器的状态和.exe的堆栈
- java - Gradle:为什么这个 build.gradle.kts 脚本无法生成任何 java 类?
- php - Laravel 6 预期的响应代码为 220,但在数字海洋上使用时得到一个空响应
- php - 我如何用 PHP 编写一个看起来像这样的 JSON 文件?
- javascript - 在函数范围外访问 var
- c++ - C++中的字符串变量
- ios - 无法进行正则表达式匹配,原因:无法打开模式
- java - 错误:包 com.google.android.gms.drive 不存在