首页 文章

如何动态加载已编译的Angular文件到路由?

提问于
浏览
1

数据库存储URL,该URL应从目录'dist'加载模块 .

{
  "personal-area": "js/compile-module.js",
  "product": "js/compile-module2.js"
}

应用实例:

http://localhost:8282/#/personal-area

然后应用程序lazy(async | dynamic | any)加载模块:

http://localhost:8282/js/compile-module.js

模块是预先编译的,并且在构建他们没有参与的主应用程序的阶段,所以我没有任何路径到角度模块的来源 .

在带路由的文件(app.routers.ts)中,我存储了组件处理程序,它从数据库中提取服务器上模块文件的路径(基于URL) .

export const ROUTES: Routes = [

    {
        path: '**',
        component: WorkspaceOutletComponent
    },

];

在主处理程序中有一个尝试加载模块的方法,但由于我不理解的原因,我不知道如何使Angular连接已编译的模块以供老鹰和工作 .

@Component({ ... })
export class WorkspaceOutletComponent {

    constructor() {
    }

    ngOnInit() {
        // detect routing and exec init
    }

    public init(workSpaceUrl: string, workSpacePathModule: string) {
        console.log(`url: ${workSpaceUrl} path: ${workSpacePathModule}`);

        this.router.resetConfig([
            {
                path: workSpaceUrl, loadChildren: workSpacePathModule
            }
        ]);

        this.router.navigate([workSpaceUrl])
            .then(() => console.log('Navigate to'))
            .catch((e) => console.error('Error', e));
    }

}

该应用程序是使用webpack 2构建的 . 但是当我更换路由时,他给我写了一个错误,我甚至不知道在哪里挖掘动态加载模块(我需要来自数据库),我这样做在组装过程中不知道模块的引用,什么都没有,我甚至没有源代码,所以我需要第三方模块加载到运行时 . 我究竟做错了什么?

enter image description here

如果我使用SystemJS . 它也没有帮助,它试图从磁盘(从源)加载模块 .

this.router.resetConfig([
            {
                path: workSpaceUrl, loadChildren: SystemJS.import(workSpacePathModule).then(function (m) {
                    console.log(m);
                })
            }
        ]);

enter image description here

这里有一点关于模块加载的工作原理:https://github.com/angular/angular-cli/issues/4234#issuecomment-275345763

我是否正确理解Angular需要一个确切的名称,以便编译哈希映射 . 这就是为什么你不能像我一样传递它,但如果我不知道磁盘上的路径之间的对应关系(因为我没有源代码),我该怎么办?

1 回答

  • 2

    不确定重置路由方式是否有效,但我知道你需要为你可能使用的所有模块生成延迟路由 .

    loadChildren 的值必须是静态 string . 你甚至无法调用那里的函数来获得 string . 即使这会混淆与Webpack一起使用的Angular CLI魔术来生成惰性路由 .

    无论如何都应该生成所有类似的惰性路由,然后在运行时加载你感兴趣的路由 . 请注意 resetConfig 可以重置整个配置 .

    还有 linkNgModuleFactory 可以为您提供模块工厂的实例(Angular在浏览器或AoT中进行编译后从模块创建的内容),您可以将其与 NgComponentOutlet 一起使用 .

相关问题