Angular 5组件迁移报错:验证组件是否属于当前模块
看起来你碰到的问题核心在于懒加载模块的独立模块上下文——Angular的懒加载模块会创建自己的注入器和模块作用域,AppModule中导入的CoreModule并不会自动被懒加载的FirstModule继承,所以FirstModule根本不知道MyComponent的存在,这就是你看到那个报错的原因。
问题根源拆解
你的CoreModule设计成了单例模块(通过构造函数里的@Optional() @SkipSelf()检查实现),只能在AppModule中导入一次。而懒加载的FirstModule是一个独立的模块,它的依赖不会自动继承AppModule的导入,所以即使CoreModule导出了MyComponent,FirstModule也访问不到。
正确的解决方案:拆分出SharedModule
既然MyComponent需要在多个模块(AppModule和FirstModule)中复用,我们应该把它从CoreModule移到一个专门的SharedModule中——SharedModule的作用就是存放可复用的组件、指令和管道,允许被多个模块导入。
步骤1:创建SharedModule
新建一个SharedModule,把MyComponent的声明和导出移到这里:
import { NgModule } from '@angular/core'; import { CommonModule } from "@angular/common"; import { MyComponent} from './components/my-component/my-component.component'; // 根据你的实际路径调整 @NgModule({ declarations: [ MyComponent ], imports: [ CommonModule ], exports: [ MyComponent ] // 导出组件,让其他模块能使用 }) export class SharedModule { }
步骤2:修改CoreModule
移除CoreModule中关于MyComponent的所有内容,保持它作为单例服务模块的职责(只存放全局服务、单例依赖):
import { NgModule, Optional, SkipSelf } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { DatePipe } from "@angular/common"; @NgModule({ imports: [ HttpClientModule ], providers: [ DatePipe ] }) export class CoreModule { constructor (@Optional() @SkipSelf() parentModule: CoreModule) { if (parentModule) { throw new Error( 'CoreModule is already loaded. Import it in the AppModule only'); } } }
步骤3:在需要的模块中导入SharedModule
- 在
AppModule中导入SharedModule(因为AppComponent之前也用到了MyComponent):// app.module.ts import { SharedModule } from './shared/shared.module'; @NgModule({ imports: [ CoreModule, SharedModule, // 其他模块... ] }) export class AppModule { } - 在懒加载的
FirstModule中也导入SharedModule:// first-module.module.ts import { SharedModule } from '../shared/shared.module'; // 路径根据实际项目结构调整 @NgModule({ declarations: [ OtherComponent ], // 你的OtherComponent imports: [ CommonModule, SharedModule, // 导入后就能在OtherComponent中使用MyComponent了 // 你的FirstModule路由模块... ] }) export class FirstModule { }
为什么不能直接把CoreModule导入FirstModule?
因为你在CoreModule的构造函数中做了单例检查,如果尝试在FirstModule中导入CoreModule,Angular会直接抛出CoreModule is already loaded的错误,这违背了CoreModule作为全局单例模块的设计初衷。
按照这个方案调整后,你就能在OtherComponent中正常使用MyComponent了~
内容的提问来源于stack exchange,提问作者codebear22

