我目前正在研究 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。
有什么办法可以解决这个错误。我知道一种方法是自行加载整个功能模块,但这不可行。
提前致谢。
最佳答案
路由应该位于与组件分开的地方,并且位于声明这些组件的模块之外。
在最长的时间里,我也遵循您使用的模式。 topic-routing.module.ts
似乎 它应该与 topic
组件一起使用。但最近我开始从不同的 Angular 思考它,而你这里的难题完美地突出了这一点。
我已经开始将 routes
视为给定应用程序的核心。当我开始编写第二个应用程序并决定重新使用我在第一个应用程序中编写的许多组件/模块时,这种范式转变就发生了。我注意到唯一没有意义的重用是路由。
就好像路由定义了“应用程序”,模块/组件是任何给定应用程序使用的构建 block 。
有鉴于此,我会推荐以下内容:
将您的路由定义从每个模块移到顶级应用程序中。它们可以位于 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)
关于 Angular 2 : Circular Feature module dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43907450/