Angular模块导入

问题描述 投票:5回答:1

我有两个模块的组件,它们互相使用,所以我必须在 "test "中导入 "word",在 "word "中导入 "test"--> 抛出一个错误。所以我必须导入 "test "中的 "word "和 "word "中的 "test"-->抛出一个错误...... 我可以怎么做?

模块 "test"。

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

模块 "word"。

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

我导入对方是因为模板。test1.component.ts的模板调用word.component.ts,word.component.ts的模板调用test1.component.ts。

test1.html的模板调用了word.component.ts。

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

word.html

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

我试着使用一个SharedModule,但我没有实现......

angular import module circular-dependency
1个回答
2
投票

也许你可以使用 "测试": @NgModule({ declarations: [... 内容投射ng-content 指令来组成嵌套组件,但这取决于你需要如何组成它们。以此为例

/ 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>

0
投票

你需要从架构上解决这个问题。

你可以创建一个同时具备这两种功能的模块......因为它们看起来是如此紧密地结合在一起,这将是我的第一选择,或者你可以将模块拆分得更细,以便一个模块的功能是另一个模块所需要的,而另一个模块则在自己的模块中。

© www.soinside.com 2019 - 2024. All rights reserved.