Angular 2 Application Structure: Circular Module Dependencies

时间:2016-10-13 18:53:00

标签: angular angular2-modules

On the Angular 2 Style Guide, there is a recommendation for a directory structure: https://angular.io/docs/ts/latest/guide/style-guide.html#04-06

我一般认为这是一个很好的建议,我打算自己做一些非常相似的事情。但是,我遇到了一个问题,我很好奇是否有人解决了它。

请注意,heroes模块包含shared目录,其中包含heroes-button.component。据推测,我们希望在整个应用程序中使用此组件(因此,“共享”)。

同样,villains模块包含shared目录,其中villains-button.component

如果我想在villains-button.component模块的某个位置使用heroes,在heroes-button.component模块中使用villains,那么我最终将会循环参考。

简而言之:Angular不允许我将ModuleA导入ModuleB,而将ModuleB导入ModuleA,但样式指南另有说明。

有没有人有这种情况的解决方案?

1 个答案:

答案 0 :(得分:2)

我对此的解决方法是将那些强制我具有循环依赖关系的组件(在本例中为villains-button.component和heroes-button.component)移动到共享模块中。

最后,目录结构如下所示:

HeroesModule
    -HeroComponentA
    -HeroComponentB
VillainsModule
     -VillainComponentA
     -VillainComponentB
SharedModule
     -HeroButton
     -Villain Button    <-- these two are now available across the application

可能感觉不对,因为您认为“Hero”按钮属于其他Hero的东西,但回想起随着我的应用程序的增长,我很高兴Angular禁止模块之间的循环依赖。随着应用程序的增长,这是一种非常危险的模式。