angularangular2-modules

Angular 2 Application Structure: Circular Module Dependencies


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

I generally think it's a good recommendation, I'd intend on doing something very similar myself. However, I've run into an issue with it, and I'm curious if anyone has resolved it.

Notice the heroes module contains a shared directory with a heroes-button.component. Presumably, we'll want to use this component all over the app (hence, "shared").

Likewise, the villains module contains a shared directory with a villains-button.component.

If I want to use the villains-button.component in some place in the heroes module and the heroes-button.component in the villains module, then I'm going to end up with a circular reference.

In short: Angular doesn't allow me to import a ModuleA into ModuleB, AND ModuleB into ModuleA, but the style guide indicates otherwise.

Does anyone have any solutions for this scenario?


Solution

  • My solution to this was to move those components that were forcing me to have a circular dependency (in this case the villains-button.component and the heroes-button.component) into the Shared module.

    In the end the directory structure looks like this:

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

    It may not feel right, because you think the "Hero" button belongs with other Hero stuff, but in retrospect as my application has grown, I'm quite glad that Angular bars circular dependencies between Modules. That is a very dangerous pattern to support as the app grows.