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

 2023-09-10 阅读 22 评论 0

摘要:核心模块CoreModule在整个系统中只加载一次,如何实现? 创建core Modele:ng g m core 既然CoreModule是类,就有构造函数,在构造函数中进行依赖注入。 export class CoreModule { constructor(parent: CoreModule){if(parent){throw new Err

核心模块CoreModule在整个系统中只加载一次,如何实现?

创建core Modele:ng g m core

既然CoreModule是类,就有构造函数,在构造函数中进行依赖注入。

export class CoreModule { constructor(parent: CoreModule){if(parent){throw new Error('模块已经存在,不能重复加载!')}}
}

使用SkipSelf注解避免重复注入。去系统的父级找依赖。

angular module、使用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就可以了。

core核心训练。 

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:https://www.cnblogs.com/starof/p/9069181.html 有问题欢迎与我讨论,共同进步。

转载于:https://www.cnblogs.com/starof/p/9069181.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/32400.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息