角圆形模块导入

时间:2018-09-18 18:24:11

标签: angular import module circular-dependency

我有两个模块,两个模块相互使用。所以我必须在“测试”中导入“单词”,在“单词”中导入“测试”->抛出错误...我该怎么办?

模块“测试”:

@NgModule({
  declarations: [
    AppTest1Component,
    AppTest2Component,
  ],
  imports: [
    AppWordModule,
  ],
  exports: [
    AppTest1Component,
    AppTest2Component,
  ],
})
export class AppTestModule {
}

模块“单词”:

@NgModule({
  declarations: [
    AppWordComponent,
  ],
  imports: [
    AppTestModule,
  ],
  exports: [
    AppWordComponent,
  ],
})
export class AppWordModule {
}

由于模板的原因,我互相导入。 test1.component.ts的模板称为word.component.ts,而word.component.ts的模板称为test1.component.ts。

test1.html

<div class="app-word"></div>

word.html

<div class="app-test1"></div>

我尝试使用SharedModule,但没有实现...

2 个答案:

答案 0 :(得分:3)

也许您可以将content projectionng-content指令一起使用来组成嵌套组件,但这取决于您需要如何组成嵌套in example

// ComposeModule

    @NgModule({
      imports: [
        CommonModule,
        AppWordModule,
        AppTestModule
      ],
      declarations: [CompositionComponent],
      exports: [CompositionComponent]
    })
    export class ComposeModule { }

// composition.component.html

    <app-word>
      <app-child-one header>
        <app-word body>
        </app-word>
      </app-child-one>
      
      <app-child-two body>
        <app-word body>
        </app-word>
      </app-child-two>
    </app-word>

// AppWordModule

    @NgModule({
      imports: [
        CommonModule
      ],
      declarations: [ WordComponent ],
      exports: [ WordComponent ]
    })
    export class AppWordModule { }

// word.component.html

    <div class="header">
      <h2>app-word:header</h2>
      <ng-content select="[header]"></ng-content>
    </div>
    <div class="body">
      <h2>app-word:body</h2>
      <ng-content select="[body]"></ng-content>
    </div>

// AppTestModule

    const COMPONENTS = [
      ChildOneComponent,
      ChildTwoComponent
    ]
    
    @NgModule({
      imports: [
        CommonModule
      ],
      declarations: [
        ...COMPONENTS
      ],
      exports: [
        ...COMPONENTS
      ]
    })
    export class AppTestModule { }

// child-one.component.html

    <div class="header">
      <h2>app-child-one:header</h2>
      <ng-content select="[header]"></ng-content>
    </div>
    <div class="body">
      <h2>app-child-one:body</h2>
      <ng-content select="[body]"></ng-content>
    </div>

// child-two.component.html

    <div class="header">
      <h2>app-child-two:header</h2>
      <ng-content select="[header]"></ng-content>
    </div>
    <div class="body">
      <h2>app-child-two:body</h2>
      <ng-content select="[body]"></ng-content>
    </div>

答案 1 :(得分:1)

您需要从架构上解决问题。

您可以创建一个具有两种功能的模块...因为它们看起来是如此紧密地结合在一起,所以这将是我的优先选择,否则,您可以进一步分解这些模块,以使一个模块所需的功能得以实现彼此都在自己的模块中。