网站搜索

angular - 动态加载延迟模块组件


我想动态加载组件,app.module 中的组件会被加载,但 lazy 模块中的组件不会。

我尝试使用这段代码。

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 加载,该模块是懒加载模块。

我发现了一些代码,我应该加载并编译懒加载模块并加载它们的组件,但我不知道具体该怎么做。