有一天,我写了一个自信满满的自定义组件myComponent,在多个页面import使用了,结果控制台给我来这个
我特么裤子都脱了,你给我来这个提示是几个意思
仔细一看 The Component 'MyComponentComponent' is declared by more than one NgModule
什么鬼?说我的组件被多个模块使用?搞什么飞机,我就是要多个页面使用呀!!!
通常出现上面这种报错都是因为使用了懒加载路由(类似下面的)
const routes: Routes = [
...
{
path: 'first',
loadChildren: () => import('./com/first/first.module').then(m => m.FirstModule),//异步加载、惰性加载、懒加载
},
...
]
于是乎查阅官方文档发现一个shared.module.ts的东东
首先找一个干净的文件夹创建一个
shared.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MyComponentComponent } from 'src/app/my-component/my-component.component';
// 这里加入自定义公共组件----------------------------------------
let declarations = [
MyComponentComponent,
];
@NgModule({
imports: [CommonModule,], //公共组件依赖的第三方组件可以在此处引入
declarations,
exports: declarations,
})
export class SharedModule { }
去需要使用相关公共组件的页面Module文件里面
first.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { FirstComponent } from './first.component';
@NgModule({
imports: [
SharedModule,//这里引入公共组件模块(共享特性模块)
RouterModule.forChild([{ path: '', component: FirstComponent }]),//这句不加不会生效
],
declarations: [FirstComponent,]
})
export class FirstModule { }
first.component.html
first
<app-my-component></app-my-component>
second.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { SecondComponent } from './second.component';
@NgModule({
imports: [
SharedModule,//这里引入公共组件模块(共享特性模块)
RouterModule.forChild([{ path: '', component: SecondComponent }]),//这句不加不会生效
],
declarations: [SecondComponent,]
})
export class SecondModule { }
second.component.html
second
<app-my-component></app-my-component>
my-component.component.html
<h1>我特么终于没报错啦!</h1>
路由自己配置好,直接访问http://localhost:4200/first
访问http://localhost:4200/second