簡體   English   中英

如何在沒有路由器的情況下動態延遲加載模塊 - Angular 9

[英]How to dynamically lazy load module without router - Angular 9

我有幾個我想動態延遲加載的模塊,我正在從 v8 升級到 v9,隨着 angular 的版本 9,有關模塊的邏輯似乎已經改變。 最好的方法是什么?

  1. 沒有模塊的組件

如果我們想動態地延遲加載一個組件(沒有模塊),那么我們可以使用與路由相同的模式:

// <ng-template #myContainer></ng-template>    
@ViewChild('myContainer', { read: ViewContainerRef }) container: ViewContainerRef;
  
const { MyLazyComponent } = await import('./path/to/lazy/component');
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyLazyComponent);
const { instance } = this.container.createComponent(componentFactory);
  1. 模塊

如果組件依賴於其他服務/組件,那么我們需要加載完整的模塊。 因為它將被延遲加載(最初未編譯)我們需要“手動”運行編譯。 它仍然比以前版本 Angular 上使用的技巧更容易。這是一個解決方案。

我們可以創建一個存儲模塊引用的服務,並將組件加載到容器中(給定模塊 ID 和容器引用)。

import { Injectable, Compiler, Injector } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class LazyComponentService {

    private componenttRefs = {
        myFirstLazyModuleId: import('../path/to/first/lazy/module/component.module'),
        mySecondLazyModuleId: import('../path/to/second/lazy/module/component.module')
    };

    constructor(
        private compiler: Compiler,
        private injector: Injector,
    ) { }

    async loadComponent(moduleId, container) {

        let ref;
        try {
            const moduleObj = await this.componenttRefs[moduleId];
            const module = moduleObj[Object.keys(moduleObj)[0]];
            const moduleFactory = await this.compiler.compileModuleAsync(module);
            const moduleRef: any = moduleFactory.create(this.injector);
            const componentFactory = moduleRef.instance.resolveComponent();
            ref = container.createComponent(componentFactory, null, moduleRef.injector);
        } catch (e) {
            console.error(e);
        }
        return ref;

    }

}

需要編譯模塊。 我們通過在每個模塊的構造函數中調用 resolveComponentFactory 來實現:

@NgModule({
  imports: [
    MyModules...
  ],
  declarations: [
    MyFirstLazyComponent
  ]
})
export class MyFirstLazyComponentModule {

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  public resolveComponent(): ComponentFactory<MyFirstLazyComponent> {
    return this.componentFactoryResolver.resolveComponentFactory(MyFirstLazyComponent);
  }

}

然后魔法出現了,你可以動態地將組件延遲加載到容器中:

  const myFirstLazyComponent = await this.lazyComponentService.loadComponent(myFirstLazyModuleId, containerRef);

我有幾個模塊想要動態延遲加載,我正在從 v8 升級到 v9,隨着 angular 版本 9,有關模塊的邏輯似乎已經改變。 最好的方法是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM