可以“ compileModuleSync”进行增量编译吗?还是可以使用其他方式?

时间:2019-01-11 06:56:34

标签: angular

我使用'ngComponentOutlet'和'Compiler.compileModuleSync'来编译带有某些组件的动态模块。我希望我可以逐步编译动态模块。或者,我可以删除组件或将组件添加到动态模块中,而不是每次都编译整个动态模块。花了很多时间。

import {Compiler, Component, Input, NgModule, NgModuleFactory, OnChanges, OnInit, SimpleChanges} from "@angular/core";
import {HTTP_INTERCEPTORS, HttpClient} from "@angular/common/http";
import {RouterModule, Routes} from '@angular/router';
import {TranslateModule, TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'uid-dynamic',
    template: `
        <ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;">
        </ng-container>
    `
})
export class DynamicComponent implements OnInit, OnChanges {

    dynamicComponent: any;
    dynamicModule: NgModuleFactory<any>;
    @Input()
    dynamicStr: string;
    @Input()
    component: string;

    constructor(private compiler: Compiler) {
    }

    ngOnChanges(changes: SimpleChanges) {
        if (changes['dynamicStr'] && !changes['dynamicStr'].isFirstChange()) {
            this._createClasses(this.dynamicStr);
        }
    }

    ngOnInit() {
        this._createClasses(this.dynamicStr);
    }

    private _createClasses(dynamicStr) {
        let tempComponents = [];
        [...there are componen code...].forEach((item) => {
            tempComponents.push(this.createNewComponent(item.code))
        });

        let dynamicComponent = this.createNewComponent(dynamicStr);
        let dynamicModule = null;
        if (dynamicComponent) {
            dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(tempComponents));
        }
        if (dynamicComponent && dynamicModule) {
            this.dynamicComponent = dynamicComponent;
            this.dynamicModule = dynamicModule;
        }
    }
    protected createComponentModule(componentTypes: any[]) {
        @NgModule({
            imports: [
                AgentModule, PerfectScrollbarModule,TranslateModule.forRoot(), LayoutModules, 
            ],
            declarations: componentTypes,
            providers: [],
            entryComponents: componentTypes
        })
        class RuntimeComponentModule {
            constructor() {  }
        }
        // a module for just this Type
        return RuntimeComponentModule;
    }
    protected createNewComponent(dynamicStr: string) {
        try {
            return eval(dynamicStr);
        } catch (e) {
            console.error('eval dynamic component source code failed: ' + e);
            return null;
        }
    }
}

使用Compiler.compileModuleSync似乎无法增量编译动态模块。我不知道还有其他方法可以使用。

0 个答案:

没有答案