组件是Angular中2个模块的声明的一部分

时间:2018-12-28 08:54:43

标签: angular typescript

我创建了一个名为 commonmod.component.ts 的组件,该组件包括在其他两个模块(abc和def)中。

abc.module.ts

import { commonmod } from '../commonmod/commonmod.component';
@NgModule({
  declarations: [
    commonmod
  ]
})

def.module.ts

import { commonmod } from '../commonmod/commonmod.component';
@NgModule({
  declarations: [
    commonmod
  ]
})

当我将abc模块中的一页重定向到def模块中的另一页时,它使我跟随以下错误。

  

错误错误:未捕获(承诺):错误:类型commonmod是2个模块的声明的一部分:abcand def!请考虑将commonmod移至导入abc和def的更高模块。您还可以创建一个新的NgModule,以导出并包括commonmod,然后在abcand def中导入该NgModule。   错误:类型commonmod是2个模块的声明的一部分:abc和def!请考虑将commonmod移至导入abcand def的更高模块。您还可以创建一个新的NgModule,将其导出并包含commonmod,然后在abc和def中导入该NgModule。

3 个答案:

答案 0 :(得分:5)

消息很清楚:您不能在多个模块中声明一个组件。 如果两个模块都需要它,则需要在第三个模块中声明/导出组件,然后将其导入abc&def。

@NgModule({
  imports:      [ MainModule ]
})
export class AbcModule { }

@NgModule({
  imports:      [ MainModule ]
})
export class DefModule { }

@NgModule({
  declarations: [ CommonMod ],
  exports:    [ CommonMod ]
})
export class MainModule { }

答案 1 :(得分:3)

一个组件只能在一个模块中声明。如果您尝试在多个模块中声明它,则会收到此错误

  

错误:类型...是2个(或更多)模块的声明的一部分:

解决此问题的方法非常简单。如果您需要在多个模块中使用某个组件,请将其添加到声明的模块的导出数组中。

所以可以说我们有一个名为 GreetingsComponent 的组件,该组件在模块 TestModule 中声明,我想在 AppComponent 中使用它在 AppModule 中声明。我将像这样将其添加到 TestModule exports 数组中

import {NgModule} from '@angular/core';
import {GreetingComponent} from './greeting.component';
@NgModule({
declarations:[GreetingComponent],
exports:[GreetingComponent]
})
export class TestModule
{
}

现在,作为 AppModule 导入 TestModule ,通过这种方式,所有构造 Components,Directive,Pipes等 TestModule exports数组中的内容将自动提供给AppModule。

AppModule.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import {TestModule} from './test.module';
import { AppComponent } from './app.component';
@NgModule({
  imports:      [ BrowserModule, FormsModule, TestModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

现在,您只需在AppComponent中使用GreetingsComponent

  <greetings></greetings>

这里工作的StackBlitz

干杯。

答案 2 :(得分:2)

如果在Angular 9+中使用HMR(热模块更换),也可能会发生这种情况。 Angular团队正在努力。

有关更多详细信息和更新,请参见this issue