【问题标题】:How to add dynamic component to Angular Router如何将动态组件添加到 Angular 路由器
【发布时间】:2019-07-07 22:30:29
【问题描述】:

我正在创建可插入的 Angular 应用程序。

我找到了以下文章:

Building an extensible Dynamic Pluggable Enterprise Application with Angular

一般来说,一切正常,但是当我尝试添加角度路由器时,我遇到了一些问题。

目前,我无法将动态加载的组件添加到路由器。

我尝试过这样的事情:

this.pluginLoader.load(pluginName).then(moduleFactory => {
              const moduleRef = moduleFactory.create(this.injector);
              const entryComponent = (moduleFactory.moduleType as any).entry;
              const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(
                entryComponent
              );

              this.router.config.push({
                path: `${pluginName}`,
                component: entryComponent
              });

              this.router.resetConfig(this.router.config);
              this.router.navigate([`/${pluginName}`]);
            });

但此代码会导致以下错误:

core.js:15723 ERROR 错误:未捕获(在承诺中):错误:未找到 function(){this.x=!1} 的组件工厂。你有没有把它添加到@NgModule.entryComponents

我也尝试过使用 loadChildren 属性而不是组件属性,但我不知道应该使用什么路径。

如何将组件添加到组件工厂,或者如何为此类组件找到合适的路径?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    我找到了一个解决方案,要将动态加载的模块添加到角度路由器,我们必须使用 LoadChildren 属性,但直接来自 Route 对象。在这种情况下,我们必须先创建 Route 对象,然后将其添加到路由器配置中。

    loadPlugin(pluginName: string) {
       this.pluginLoader.load(pluginName).then(moduleFactory => {
    
          const route: Route = {
              path: `${pluginName}`,
              loadChildren: () => moduleFactory
          };
    
          this.router.config.push(route);
       });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 2020-08-09
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多