核心模塊CoreModule在整個系統中只加載一次,如何實現?
創建core Modele:ng g m core
既然CoreModule是類,就有構造函數,在構造函數中進行依賴注入。
export class CoreModule { constructor(parent: CoreModule){ if(parent){ throw new Error('模塊已經存在,不能重復加載!') } } }
使用SkipSelf注解避免重復注入。去系統的父級找依賴。
使用Optional注解 讓SkipSelf作為可選,在第一次注入時候系統中並沒有CoreModule時候成功注入。
import { NgModule,SkipSelf,Optional} from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ imports: [ CommonModule ], declarations: [] }) export class CoreModule { constructor(@Optional() @SkipSelf() parent: CoreModule){ //加上@SkipSelf()注解 if(parent){ throw new Error ('模塊已經存在,不能再次加載'); } } }
后續加了模塊,后在declartions中聲明后需要在exports中導出。
Header,Footer,Sidebar放到核心模塊中。
ng g c core/header --spec=false ng g c core/footer --spec=false ng g c core/sidebar --spec=false
然后
import { NgModule,SkipSelf,Optional} from '@angular/core'; import { CommonModule } from '@angular/common'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { SidebarComponent } from './sidebar/sidebar.component'; @NgModule({ imports: [ CommonModule ], declarations: [HeaderComponent, FooterComponent, SidebarComponent], exports:[ HeaderComponent, FooterComponent, SidebarComponent ] }) export class CoreModule { constructor(@Optional() @SkipSelf() parent: CoreModule){ //加上@SkipSelf()注解 if(parent){ throw new Error ('模塊已經存在,不能再次加載'); } } }
這樣只需要在app.module.ts中imports coreModule就可以了。
本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:https://www.cnblogs.com/starof/p/9069181.html 有問題歡迎與我討論,共同進步。