【问题标题】:Can not load component in Angular?无法在 Angular 中加载组件?
【发布时间】:2017-08-05 10:05:41
【问题描述】:

页面加载时出现错误:

compiler.es5.js:1690 Uncaught Error: Type LoginComponent is part of the declarations of 2 modules: LoginModule and AppModule! Please

考虑将 LoginComponent 移至导入的更高模块 登录模块和应用模块。你也可以创建一个新的 NgModule 导出并包含 LoginComponent 然后将该 NgModule 导入 LoginModule 和 AppModule。

@NgModule 我有以下声明:

declarations: [AppComponent, LoginComponent, LanguageComponent]

如何解决这个问题?

在文件 app.module 的顶部我有导入:

import { LanguageComponent } from './language/language.component';
import  { LoginComponent } from "./login/login.component";

以下部分:

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    TranslateModule.forRoot(),
    NgbModule.forRoot(),
    CoreModule,
    SharedModule,
    HomeModule,
    AboutModule,
    LoginModule,
    AppRoutingModule,
    InMemoryWebApiModule,
    LocalStorageModule,
    ReactiveFormsModule,
    ReCaptchaModule,
    TextMaskModule,
    MdButtonModule,
    MdCheckboxModule
  ],

  declarations: [AppComponent, LoginComponent, LanguageComponent],
  providers: [
    AuthenticationService,
    HiderPipe,
    TimerService
  ],
  bootstrap: [AppComponent]
})

【问题讨论】:

  • 更多代码肯定会有所帮助
  • 组件也需要在 ngModule 的exports 中。
  • 并粘贴整个 NgModule
  • 看起来很简单,从 AppModule 的声明中删除 LoginComponent,因为它已经是 LoginModule 的一部分。
  • 它明确指出LoginComponent 在 2 个模块中声明。我假设该组件只会在LoginModule 中使用,因此在AppModule 中声明它是没有意义的。从那里删除它。

标签: angular


【解决方案1】:

当你想将一个组件用于另一个模块时,你必须做以下事情。假设 Login 组件在 LoginModule 中,为了在模块之外使用这个组件声明和导出组件。如果不导出组件,则不能在 UserModule 之外使用组件

@NgModule({
  imports:[RouterModule,BrowserModule,FormsModule],
  declarations:[LoginComponent],
  exports: [LoginComponent],
})
export class LoginModule {

 }

然后你就不需要在 App 模块中再次声明 LoginComponent 了。只需导入 LoginComponent 所在的 LoginModule。

 @NgModule({
      imports:[RouterModule,BrowserModule,FormsModule,LoginModule],
      declarations:[],
      exports: [],
    })
    export class AppModule {

     }

【讨论】:

  • 我也是这么说的,他的回答是“我在这里添加,没有它们也不行”:D :D
【解决方案2】:

loginModuel 的双重导入。
您必须在导入中删除 loginModuel:[]

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2018-08-12
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2018-06-17
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多