Angular 2:循环依赖的特性模块

6

我目前正在开发Angular2的一个应用程序。其中包含3个功能模块,这些模块包含其他子功能模块。 我希望将功能1的子功能模块加载到功能2的子功能模块中,反之亦然。以下是示例代码。

action-routing.module.ts

const routes: Routes = [
    {
        path: '',
        component: ActionComponent,
        children: [
          {
           path: ':id',
           loadChildren: 'app/action/action-detail/action-detail.module#ActionDetailModule'
          }
        ]
     }
];

action-detail-routing.module.ts

const routes: Routes = [
    {
        path: '',
        component: ActionDetailComponent,
    },    
    {
        path: 'topic-detail/:id',
        loadChildren: 'app/topic/decision-topic-detail/decision-topic-detail.module#DecisionTopicDetailModule',
    }
]

topic-routing.module.ts

const routes: Routes = [
    {
        path: '',
        component: TopicComponent,
        children: [
          {
           path: ':id',
           loadChildren: 'app/topic/decision-topic-detail/decision-topic-detail.module#DecisionTopicDetailModule'
          }
        ]
     }
];

decision-topic-detail-routing.module.ts

const routes: Routes = [
    {
        path: '',
        component: DecisionTopicDetailComponent,
    },    
    {
        path: 'action-detail/:id',
        loadChildren: 'app/action/action-detail/action-detail.module#ActionDetailModule'
    }
]

这会创建循环依赖,并在编译期间抛出ERROR in Maximum call stack size exceeded错误。

有没有解决此错误的方法。我知道一种方法是加载整个功能模块本身,但那并不可行。

提前感谢。


这是Angular CLI中的一个错误。https://github.com/angular/angular-cli/issues/6309 - Parikh Vaibhav
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
1

路由应该存在于一个与组件分离的位置,并且在这些组件声明的模块之外。

最长一段时间里,我也遵循了你使用的模式。 topic-routing.module.ts 似乎 应该和 topic 组件一起存在。但是最近我开始从不同的角度思考它,而你在这里的困境正好突显了这一点。

我开始将 routes 视为给定应用程序的核心。当我开始编写第二个应用程序并决定重复使用我在第一个应用程序中编写的许多组件/模块时,我注意到唯一没有意义重复使用的是路由。

好像路由定义了“应用程序”,而模块/组件是任何给定应用程序要使用的构建块。

在这种情况下,我建议:

将路由定义从每个模块中移出到顶层应用程序中。他们可以存在于 app.routes 旁边的一个目录中,并且您可以将它们分布在其当前文件中,或者如果您没有那么多,您可以将它们合并到同一个文件中。

虽然这似乎与直觉相反,并且你失去了“垂直”分组,其中所有的topic内容都随主题一起,所有的action内容都随操作一起。但是当你把路由看作是与它们所指的组件根本不同的东西时,这就不那么痛苦了,而且肯定可以解决你的问题。
src
  |-app.component.ts
  |-app.component.html
  |-app.routes.ts  <-- includes the routes in the sibling directory
  |-routing
      |- action.routes.ts
      |- action-detail.routes.ts
      |- topic.routes.ts
      \- decision-topic-detail.ts
  |-decision-topic-detail (module)
  |-topic (module)
  \-action (module)

如果我在顶层编写所有路由,那么我不会失去Angular2的惰性加载功能吗? - Parikh Vaibhav
我尝试了你的解决方案,但它并没有帮助,因为实际问题在于action-detail模块被导入到topic模块中,反之亦然。请参见下面的git链接: https://github.com/vaibhavbparikh/circular-routes/tree/seperate-routes - Parikh Vaibhav
1
@ParikhVaibhav,我原以为你将action-detail模块导入到topic模块中的唯一原因是因为你想在模块之间共享路由。如果不是因为路由,那么你有循环依赖的原因是什么?模块不能有循环依赖;如果你在B中包含A,那么B中就不应该有任何A需要的内容,否则这是一个设计缺陷。 - Daniel Patrick
1
我想要将子模块导入到其他模块中,而不需要加载主模块。请查看此存储库:https://github.com/vaibhavbparikh/circular-routes。另外,Angular cli存在一些错误已经被报告,请参见问题评论中的链接。如果这可能是设计缺陷,您能帮我确定最佳实践吗? - Parikh Vaibhav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,