动态加载延迟模块组件

时间:2018-05-28 07:10:45

标签: angular typescript components

我想动态加载组件,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加载组件,LabModule是一个惰性模块。

我发现了一些代码,我应该加载并编译惰性模块并加载它们的组件,但我不知道如何完成它。

0 个答案:

没有答案