Angular 角常春藤:读取模块提供程序
我正试着在有角度的常春藤中延迟加载一个组件Angular 角常春藤:读取模块提供程序,angular,angular-ivy,Angular,Angular Ivy,我正试着在有角度的常春藤中延迟加载一个组件 import("./app/products/products.module").then((module) => { console.log(module.ProductsModule.ngInjectorDef.providers); }); 模块代码 import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; imp
import("./app/products/products.module").then((module) => {
console.log(module.ProductsModule.ngInjectorDef.providers);
});
模块代码
import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { LazyComponent } from "./lazy/lazy.component";
@NgModule({
declarations : [LazyComponent],
imports : [
CommonModule
],
entryComponents: [
LazyComponent
],
providers : [
{
provide : "components",
useValue: {
lazy: LazyComponent,
}
}
]
})
export class ProductsModule {
}
我可以使用module.ProductsModule.nginjectDef.providers
访问提供程序,但我正在寻找更好的方法
也许像
module.ProductsModule.ngInjectDef.get(“组件”)
Ivy有一个名为createInjector
的私有函数,它在当前API中与θ一起公开,但在Ivy稳定后将公开
假设您有这样的代码:
@NgModule({
声明:[LazyComponent],
供应商:[
{
提供:'组件',
使用价值:{
懒散的:懒散的
}
}
],
入口组件:[懒散组件]
})
导出类LazyModule{
静态getLazyComponents:()=>{lazy:typeof LazyComponent};
建造师(注入器:注入器){
LazyModule.getLazyComponents=()=>injector.get('components');
}
}
让我们通过动态导入延迟加载LazyModule
:
从'@angular/core'导入{ɵcreateInjector as createInjector,Injector};
导出类AppComponent{
建造师(注入器:注入器){
导入('./lazy/lazy.module')。然后({LazyModule})=>{
创建注入器(LazyModule,注入器);
log(LazyModule.getLazyComponents());
});
}
}
但是使用这种方法,您可以延迟加载一个模块。如果您想延迟加载组件-您可以不使用模块来完成,假设此LazyComponent
,位于lazy.component.ts
文件中:
@组件({
选择器:“应用程序惰性”,
模板:`
我很懒
`
})
导出类LazyComponent{}
您可以使用动态导入加载此组件+renderComponent
功能:
从'@angular/core'导入{ɵrenderComponent作为renderComponent,Injector};
@组成部分({
选择器:'应用程序根',
模板:`
`
})
导出类AppComponent{
建造师(注入器:注入器){
导入('./lazy.component')。然后({LazyComponent})=>{
渲染组件(懒散组件{
注射器,
主持人:“应用程序懒惰”
});
});
}
}
一个注意事项-惰性组件没有生命周期<将调用code>constructor,但不会调用诸如ngOnInit
、ngondestory
等钩子
回到您关于懒惰模块的问题——您可能希望公开这些懒惰组件的组件工厂,类似这样:
导出类LazyModule{
静态GetComponentFactorys:()=>{
懒惰:组件工厂;
};
构造函数(解析程序:ComponentFactoryResolver){
LazyModule.GetComponentFactorys=()=>({
lazy:resolver.resolveComponentFactory(LazyComponent)
});
}
}
如果不想使用静态函数,可以声明实例方法:
导出类LazyModule{
构造函数(专用冲突解决程序:ComponentFactoryResolver){}
公共getComponentFactorys(){
返回{
lazy:this.resolver.resolveComponentFactory(LazyComponent)
};
}
}
然后获取此模块的一个实例:
导出类AppComponent{
构造函数(专用注入器:注入器){
导入('./lazy/lazy.module')。然后({LazyModule})=>{
const injector=createInjector(LazyModule,this.injector);
const lazyModule=注射器.get(lazyModule);
log(lazyModule.getComponentFactorys());
});
}
}
谢谢,一百年后我想不出:D@UnLoCo哈哈:是的,我建议你只要复制θ符号,然后按住ctrl+f键就可以探索常春藤的API了