日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?

發布時間:2023/11/27 生活经验 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

有一天,我寫了一個自信滿滿的自定義組件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

?

?

總結

以上是生活随笔為你收集整理的Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。