所以嘿,
我试图遵循这些指南:https : //angular.io/guide/lazy-loading-ngmodules
但是官方文档只涵盖了路由器(哇。Qngular 文档是次优的)
https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093
所以这篇中等文章正是我正在寻找的。我唯一的问题是它不起作用。
角度.JSON
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"lazyModules": [
"path/to/components#MyModule"
],
应用模块
providers: [
SystemJsNgModuleLoader, // without this I get NullInjectorError
CookieService,
{ provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader }, // this doesnt seem to do anything
{
provide: HTTP_INTERCEPTORS, useClass: AuthHeaderInterceptor, multi: true,
}
],
bootstrap: [AppComponent]
模块
@NgModule({
imports: [
CommonModule,
MatButtonModule,
MatIconModule,
],
declarations: [
MyModule.rootComponent
],
providers: [MyService],
entryComponents: [MyModule.rootComponent]
})
export class MyModule{
static rootComponent = MyComponent;
static forRoot(): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [MyService]
};
}
}
服务
@Injectable()
export default class MyService {}
...
懒惰的负载提供者
export interface LAZY_MODULES {
'MyModule': string;
}
export const lazyMap: LAZY_MODULES = {
'MyModule': 'path/to/components#MyModule'
};
export const LAZY_MODULES_MAP = new InjectionToken('LAZY_MODULES_MAP', {
factory: () => lazyMap
})
延迟加载指令
@Directive({
selector: '[lazyLoadModule]'
})
export class LazyLoadModuleDirective implements OnInit, OnDestroy {
@Input('lazyLoadModule') moduleName: keyof LAZY_MODULES;
private moduleRef: NgModuleRef<any>;
constructor(
private vcr: ViewContainerRef,
private injector: Injector,
private loader: NgModuleFactoryLoader,
@Inject(LAZY_MODULES_MAP) private modulesMap
) { }
ngOnInit() {
this.loader
.load(this.modulesMap[this.moduleName])
.then((moduleFactory: NgModuleFactory<any>) => {
this.moduleRef = moduleFactory.create(this.injector);
const rootComponent = (moduleFactory.moduleType as ModuleWithRoot)
.rootComponent;
const factory = this.moduleRef.componentFactoryResolver.resolveComponentFactory(
rootComponent
);
this.vcr.createComponent(factory);
});
}
ngOnDestroy() {
this.moduleRef && this.moduleRef.destroy();
}
}
在应用程序组件 HTML
<ng-container *ngIf="showModule"
lazyLoadModule="MyModule">
</ng-container>
所以结果是:
如果我使用没有包装器对象的 SystemJsNgModuleLoader,Chunking 工作(webpack 报告说它构建了一个path-to-components-my-module.ts)在开发工具中,我得到 SystemJsNgModuleLoader 的 NullinjectorError
如果我直接在提供程序中使用 SystemJsNgModuleLoader,我不会在开发控制台中收到错误消息。分块也有效。但是在网络控制台中,模块永远不会被加载,即使我直接在应用程序控制器中设置 showModule=true ...
上面的例子有效。该指南简单地假设每个人都记得将加载器组件添加到根模块中。
有趣的是没有抛出错误(因为它是一个指令,而不是一个元素)并且系统只是假设 lazyLoadModule 是一个允许的 HTML 属性?无论如何修复:
@NgModule({
declarations: [
...,
LazyLoadModuleDirective
]
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句