Angular项目中核心模块core Module只加载一次的实现

本文介绍如何在Angular应用中确保CoreModule仅被加载一次,通过使用@SkipSelf和@Optional注解避免重复加载,并展示了如何将通用组件Header、Footer和Sidebar包含在CoreModule中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心模块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 有问题欢迎与我讨论,共同进步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值