我正在构建一个角度4应用程序 . 我收到错误组件HomeComponent不是任何NgModule的一部分或模块尚未导入您的模块 . 我创建了HomeModule和HomeComponent . 我需要在AppModule中引用哪一个 . 我有点困惑 . 我是否需要参考HomeModule或HomeComponent . 最终我要找的是当用户点击主菜单时,他应该被定向到将在索引页面上呈现的home.component.html .
App.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http'
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
@NgModule({
declarations: [
AppComponent,
FooterbarComponent,
TopbarComponent,
NavbarComponent
],
imports: [
BrowserModule,
HttpModule,
AppRoutingModule,
HomeModule
],
providers: [MRDBGlobalConstants],
bootstrap: [AppComponent]
})
export class AppModule { }
HomeModule
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home.component';
@NgModule({
imports: [
CommonModule
],
exports: [HomeComponent],
declarations: [HomeComponent]
})
export class HomeModule { }
HomeComponent
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
6 回答
如果您没有使用延迟加载,则需要在app.module中导入HomeComponent并在声明下提及它 . 另外,不要忘记从导入中删除
在我的情况下,我只需要重新启动服务器(即如果你正在使用
ng serve
) .每次我在服务器运行时添加新模块时都会发生这种情况 .
我有同样的问题 . 原因是因为我在服务器仍在运行时创建了一个组件 . 解决方案是退出服务器并再次使用ng服务 .
在我的情况下,
app.component.spec.ts
中的实际路由导入导致了这些错误消息 . 解决方法是导入RouterTestingModule
.我遇到了同样的问题,我在这里看到的一切都没有奏效 . 如果您在app-routing.module问题中列出您的组件,您可能遇到了我遇到的同样问题 .
app.module.ts
家用/ index.ts
APP-routing.module.ts
家用/ home.module.ts
我不会声称理解为什么会出现这种情况,但是当使用索引来导出组件时(我会假设服务等相同),当在单独的模块中引用相同的组件时,您需要从相同的文件,在这种情况下是索引,以避免此问题 .
在我的情况下,Angular 6,我重命名了我的模块的文件夹和文件名 from google.map.module.ts to google-map.module.ts. 为了编译没有覆盖旧模块和组件名称,ng编译器编译没有错误 .
在app.routes.ts中:
在google-map.routing.ts中
在google-map.module.ts中: