微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 --prod 选项

如何解决使用 --prod 选项

我有一个 Angular 应用程序,我最近将它从版本 8 升级到了版本 11。在升级之前,一切正常。在这个应用程序中,有一些组件是通过 Angular 中的 ComponentFactoryResolver 类动态加载的。有一个特殊的装饰器,可以将具有特殊名称的组件类保存到 Map 对象中,以便稍后加载它们。装饰器看起来像这样:

export default function PluginView(name: string) {
    return (ctor: new () => PluginBase) => {
        PluginViewManager.addpluginView(name,ctor);
    };
}

export class PluginViewManager {
    private static pluginViewByUniqueName = new Map<string,new () => PluginBase>();

    public static addpluginView(name: string,plugin: new () => PluginBase) {
        const uniqueName = name.toLowerCase();
        if (!this.pluginViewByUniqueName.has(uniqueName)) {
            this.pluginViewByUniqueName.set(uniqueName,plugin);
        }
    }

    public static getPluginView(uniqueName: string): new () => PluginBase {
        return this.pluginViewByUniqueName.get(uniqueName.toLowerCase());
    }
}

问题是因为动态加载的组件从未使用过,它们不会在 Angular 生产构建中加载,因此不会调用装饰器。有什么办法可以强制 Angular 编译器加载一些特殊的组件而不在那里做任何优化吗?

编辑 1:
动态加载器组件的代码如下:
HTML 文件

<ng-template component-host></ng-template>

<button *ngFor="let name of names" (click)="loadComponentByUniqueName(name)">{{ name }}</button>

TS 文件

export class ComponentLoaderComponent implements AfterViewInit,OnDestroy,OnChanges {
    public names: string[] = [];

    @ViewChild(ComponentDirective)
    private componentHost: ComponentDirective;

    constructor(
        public elementRef: ElementRef<HTMLElement>,private componentFactoryResolver: ComponentFactoryResolver,private chRef: ChangeDetectorRef
    ) {
        this.names = PluginViewManager.getPluginUniqueNames();
    }

    public loadComponentByUniqueName(uniqueName: string): PluginBase {
        let instance: PluginBase;

        const loadedComponent = this.loadComponent<PluginBase>(plugin,this.visualizerService.currentView);
        instance = loadedComponent.instance;

        this.chRef.detectChanges();
        return instance;
    }

    public loadComponent<T>(view: new () => PluginBase): { instance: T,componentRef: ComponentRef<any> } {
        let instance: T;

        const factory = this.componentFactoryResolver.resolveComponentFactory(view);
        const factoryClass = factory && factory.componentType;

        let componentRef: ComponentRef<any> = null;

        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(factoryClass);
        componentRef = this.componentHost.viewContainerRef.createComponent(componentFactory);

        instance = <T>componentRef.instance;

        return { instance: instance,componentRef: componentRef };
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。