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

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

posted @ 2018-05-21 20:33  starof  阅读(2875)  评论(0编辑  收藏  举报