项目工程结构搭建

来源:互联网 发布:网络优化论文3000字 编辑:程序博客网 时间:2024/05/11 16:33

ng new taskmgr –skip-install –style=scss 或者用 缩写
npm new taskmgr -si –style=scss
希望项目的样式风格是scss而不是css,因为后面会用Angular Material做主题的支持

cd taskmgr 进入目录文件
code . 启动 Visual code IDE

ng g m core 新建核心模块,这个模块我想让它在系统中只加载一次
既然CoreModule是一个类,那么它就会有构造函数,然后我们就可以在构造函数当中去进行依赖性注入

举个栗子:core.module.ts
CoreModule代码:

//这里特殊引入了SkipSelf,import { NgModule, SkipSelf ,Optional} from '@angular/core';import { CommonModule } from '@angular/common';@NgModule({  imports: [    CommonModule  ],  declarations: []})export class CoreModule {  //@SkipSelf()这个注解是告诉说不要在我这里打转转了,去系统我的父级去寻找我的依赖,如果我已经存在了,那么在我的父亲的依赖池里面就会有我了,你去那里面找我,这样就可以避免无限循环了  //第一次进入的时候,系统当中并没有CoreModule,所以用@Optional()告诉说这个依赖是可选的,当CoreModule不存在时,那就正常运行构造就好了。当存在时,那抛出一个异常就好了  constructor(@Optional() @SkipSelf() parent: CoreModule) {    if (parent){      throw new Error('模块已经存在,不能再次加载');    } else {    }   } }

ng g m shared 新建共享模块,就是把大家都需要的东西导入进来,再导出出去。
举个栗子:shared.module.ts
SharedModule代码:

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';@NgModule({  imports: [    CommonModule  ],  exports: [    CommonModule  ],  declarations: []})export class SharedModule { }

在这里我们把 CommonModule导入进来再导出出去,这样的话以后再有其它的模块需要 CommonModule的时候我们只需要导入SharedModule就好了,随着项目的增长,SharedModule里面会有很多模块需要导入导出。如果分别在每一个模块中导入导出就会很烦,再一个作用就是这个模块中后面也会有其它大家共享的组件

接下来:

在app.module.ts 根模块当中我们需要把CoreModule模块导入进来,这样我们在根模块中加载一次,其它的时候就不加载了

举个栗子:core.module.ts
CoreModule代码:

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import {CoreModule} from './core/core.module'import { AppComponent } from './app.component';@NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    CoreModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
原创粉丝点击