4

在 Angular 网站中有新的 api SystemJsNgModuleLoader

有谁知道我如何使用这个 api 在应用程序中加载动态模块?

4

2 回答 2

2

我知道您会找到解决方案,但为了其他人的参考,我提供了解决方案。该代码已得到很好的注释,并且易于理解。

createComponent(fileName, componentName){
    let injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    // 1. Create module loader
    let loader = new SystemJsNgModuleLoader(this.compiler);
    loader.load(fileName).then((nmf:NgModuleFactory<any>)=>{
        // 2. create NgModuleRef
        let ngmRef = nmf.create(injector);
        // 3. Create component factory
        let cmpFactory = ngmRef.componentFactoryResolver.resolveComponentFactory( componentName );
        // 4. Create the component
        let componentRef = this.span.createComponent(cmpFactory,0,injector,[]);
        // 5. Init the component name field.
        componentRef.instance.name = "Some Name";
        // 6. Refresh the component area.
        componentRef.changeDetectorRef.detectChanges();
        componentRef.onDestroy(()=> {
            componentRef.changeDetectorRef.detach();
        });
    });
}

通过使用上述函数,我们可以从任何来源注入模块。更多请参考this

于 2017-02-17T09:39:29.127 回答
0

我发现了几个使用 SystemJsNgModuleLoader 的例子。

Angular2 + 从路径动态加载模块和组件。: https ://embed.plnkr.co/khdS8xFkvqe7ZIsz0kc7/

Angular2 + SystemJsNgModuleLoader 测试: https ://embed.plnkr.co/mgdBhKpCVI1LRQ2l81pC/

在运行时动态导入模块: https ://myview.rahulnivi.net/dynamically-importing-modules-runtime/

另一种延迟加载外部库的方法: https ://github.com/angular/angular-cli/issues/6373

从 node_modules 延迟加载特征库模块: https ://github.com/angular/angular/issues/25083

为什么以及如何延迟加载 Angular 库: https ://medium.com/@tomastrajan/why-and-how-to-lazy-load-angular-libraries-a3bf1489fe24

我希望这会有所帮助。

谢谢,吉涅什·拉瓦尔

于 2019-06-07T07:11:37.850 回答