目录 css
1、 前言 html
1.1. 规范目的 前端
1.2. 局限性 编程
2、 文件规范 json
2.1. 文件结构约定 api
2.2. 单一职责原则 缓存
2.2.1 单一规则 前端框架
2.2.2 小函数 服务器
3、 命名规范 前端工程师
3.1. 整体命名原则
3.2. 使用点和横杠来分隔文件名
3.3. 符号名与文件名
3.4. 服务名
3.5. 引导程序
3.6. 组件选择器
3.7. 组件的自定义前缀
3.8. 指令选择器
3.9. 指令的自定义前缀
3.10. 管道名
3.11. 单元测试文件名
3.12. 端到端(E2E)测试的文件名
3.13. Angular NgModule 命名
4、 编程规范
4.1. 类
4.2. 常量
4.3. 接口
4.4. 属性和方法
4.5. 导入语句中的空行
4.6. 注释
4.7. 优化做用域链
4.8. 合并http请求
4.9. 业务分离
5、 应用程序结构与 NgModule
5.1. LIFT
5.1.1 定位
5.1.2 识别
5.1.3 扁平
5.1.4 T-DRY
5.2. 整体结构的指导原则
5.3. 按特性组织的目录结构
5.4. 应用的根模块
5.5. 特性模块
5.6. 共享特性模块
5.7. 核心特性模块
5.8. 防止屡次导入 CoreModule
5.9. 惰性加载的目录
5.10. 不要直接导入惰性加载的目录
6、 Components
6.1. 把组件当作元素
6.2. 把模板和样式从组件中分离
6.3. 内联输入和输出属性装饰器
6.4. 避免为输入和输出属性指定别名
6.5. 成员顺序
6.6. 把逻辑放到服务里
6.7. 不要给输出属性加前缀
6.8. 把表现层逻辑放到组件类里
7、 指令
7.1. 使用指令来加强已有元素
7.2. HostListener、HostBinding 装饰器 和 组件元数据 host
8、 服务
8.1. 服务老是单例的
8.2. 单一职责
8.3. 提供一个服务
8.4. 使用 @Injectable() 类装饰器
9、 数据服务
9.1. 经过服务与 Web 服务器通信
10、 生命周期钩子
10.1. 实现生命周期钩子接口
1、 前言
为提升团队协做效率,提升代码的可读性、可复用性和可移植性,便于前端输出高质量的代码以及后期优化维护,特制订此文档。
本文着重结合了Angular(CLI 7.2.2)这一前端框架(版本)进行规范,虽然部分规范对于原生JavaScript开发或其余前端框架依然适用,但也有部分规范并不通用,所以本文主要面向基于 Angular (CLI 7.2.2)框架进行开发的Web前端工程师。
2、 文件规范
在后述代码例子中,有的文件有一个或多个类似名字的配套文件。(例如 hero.component.ts 和 hero.component.html)。
本文将会使用像 hero.component.ts|html|css|spec 的简写来表示上面描述的多个文件,目的是保持本指南的简洁性,增长描述文件结构时的可读性。
对全部的组件、服务等等应用单一职责原则 (single responsibility principle,SRP)。这样可让应用更干净、更易读、更易维护、更易测试。
由于:
1) 单组件文件很是容易阅读、维护,并能防止在版本控制系统里与团队冲突。
2) 单组件文件能够防止一些隐蔽的程序缺陷,当把多个组件合写在同一个文件中时,可能形成共享变量、建立意外的闭包,或者与依赖之间产生意外耦合等状况。
3) 单独的组件一般是该文件默认的导出,能够用路由器实现按需加载。
4) 最关键的是,能够加强代码可重用性和阅读性,减小出错的可能性。
由于:
1) 简单函数更易于测试,特别是当它们只作一件事,只为一个目的服务时。
2) 简单函数促进代码重用。
3) 简单函数更易于阅读。
4) 简单函数更易于维护。
5) 简单函数可避免易在大函数中产生的隐蔽性错误,例如与外界共享变量、建立意外的闭包或与依赖之间产生意外耦合等。
3、 命名规范
命名约定对可维护性和可读性很是重要。本文为文件名和符号名制定了一套命名约定。
由于:
1) 命名约定提供了一致的方式来查找内容,让你一眼就能找到。 项目的一致性是相当重要的。团队内的一致性也很重要。整个公司的一致性会提供惊人的效率。
2) 命名约定帮助你更快得找到想找的代码,也更容易理解它。
3) 目录名和文件名应该清楚的传递它们的意图。例如,app/heroes/hero-list.component.ts 包含了一个用来管理英雄列表的组件。
由于:
1) 类型名字提供一致的方式来快速的识别文件中有什么。
2) 利用编辑器或者 IDE 的模糊搜索功能,能够很容易地找到特定文件。
3) 像 .service 这样的没有简写过的类型名字,描述清楚,绝不含糊。 像 .srv, .svc, 和 .serv 这样的简写可能使人困惑。
4) 为自动化任务提供模式匹配。
由于:
1) 遵循一致的约定能够快速识别和引用不一样类型的资源。
符号名 |
文件名 |
@Component({ ... }) export class AppComponent { } |
app.component.ts |
@Component({ ... }) export class HeroesComponent { } |
heroes.component.ts |
@Component({ ... }) export class HeroListComponent { } |
hero-list.component.ts |
@Component({ ... }) export class HeroDetailComponent { } |
hero-detail.component.ts |
@Directive({ ... }) export class ValidationDirective { } |
validation.directive.ts |
@NgModule({ ... }) export class AppModule |
app.module.ts |
@Pipe({ name: 'initCaps' }) export class InitCapsPipe implements PipeTransform { } |
init-caps.pipe.ts |
@Injectable() export class UserProfileService { } |
user-profile.service.ts |
由于:
1) 提供一致的方式来快速识别和引用服务。
2) 像 Logger 这样的清楚的服务名不须要后缀。
3) 像 Credit 这样的,服务名是名词,须要一个后缀。当不能明显分辨它是服务仍是其它东西时,应该添加后缀。
符号名 |
文件名 |
@Injectable() export class HeroDataService { } |
hero-data.service.ts |
@Injectable() export class CreditService { } |
credit.service.ts |
@Injectable() export class Logger { } |
logger.service.ts |
由于:
1) 应用的启动逻辑遵循一致的约定。
2) 这是从其它技术平台借鉴的经常使用约定。
坚持使用短横线命名法(dashed-case)或叫烤串命名法(kebab-case)来命名组件的元素选择器,让元素名和自定义元素规范保持一致。
由于:
1) 防止与其它应用中的组件和原生 HTML 元素发生命名冲突。
2) 更容易在其它应用中推广和共享组件。
3) 组件在 DOM 中更容易被区分出来。
@Component({ selector: 'toh-hero-button', templateUrl: './hero-button.component.html' }) export class HeroButtonComponent {}
由于:
1) 可让指令中的属性名与视图中绑定的属性名保持一致。
2) Angular 的 HTML 解析器是大小写敏感的,能够识别小驼峰形式。
由于:
1) 防止名字冲突。
2) 指令更加容易被识别。
@Directive({ selector: '[tohValidate]' }) export class ValidateDirective {}
由于:
1) 提供一致方式快速识别和引用管道。
符号名 |
文件名 |
@Pipe({ name: 'ellipsis' }) export class EllipsisPipe implements PipeTransform { } |
ellipsis.pipe.ts |
@Pipe({ name: 'initCaps' }) export class InitCapsPipe implements PipeTransform { } |
init-caps.pipe.ts |
由于:
1) 提供一致的方式来快速识别测试。
2) 提供一个与 karma 或者其它测试运行器相配的命名模式。
测试类型 |
文件名 |
组件 |
heroes.component.spec.ts hero-list.component.spec.ts hero-detail.component.spec.ts |
服务 |
logger.service.spec.ts hero.service.spec.ts filter-text.service.spec.ts |
管道 |
ellipsis.pipe.spec.ts init-caps.pipe.spec.ts |
由于:
1) 提供一致的方式快速识别端到端测试文件。
2) 提供一个与测试运行器和构建自动化匹配的模式。
测试类型 |
文件名 |
端到端测试 |
app.e2e-spec.ts heroes.e2e-spec.ts |
由于:
1) 提供一致的方式来快速标识和引用模块。
2) 大驼峰命名法是一种命名约定,用来标识可用构造函数实例化的对象。
由于:
1) RoutingModule 是一种专门用来配置 Angular 路由器的模块。 “类名和文件名保持一致”的约定使这些模块易于发现和验证。
符号名 |
文件名 |
@NgModule({ ... }) export class AppModule { } |
app.module.ts |
@NgModule({ ... }) export class HeroesModule { } |
heroes.module.ts |
@NgModule({ ... }) export class VillainsModule { } |
villains.module.ts |
@NgModule({ ... }) export class AppRoutingModule { } |
app-routing.module.ts |
@NgModule({ ... }) export class HeroesRoutingModule { } |
heroes-routing.module.ts |
4、 编程规范
坚持一致的编程、命名和空格的约定。
坚持使用大写驼峰命名法来命名类。
由于:
1) 遵循类命名传统约定。
2) 类能够被实例化和构造实例。根据约定,用大写驼峰命名法来标识可构造的东西。
export class ExceptionService { constructor() { } }
由于:
1) 告诉读者这个值是不可变的。
2) TypeScript 会要求在声明时当即初始化,并阻止再次赋值,以帮助确保你的设计意图。
由于:
1) 小驼峰变量名 (heroRoutes) 比传统的大写蛇形命名法 (HERO_ROUTES) 更容易阅读和理解。
2) 把常量命名为大写蛇形命名法的传统源于现代 IDE 出现以前, 以便阅读时能够快速发现那些 const 定义。 TypeScript 自己就可以防止意外赋值。
由于:
1) 传统的大写蛇形命名法仍然很流行、很广泛,特别是在第三方模块中。 修改它们没多大价值,还会有破坏现有代码和文档的风险。
export const mockHeroes = ['Sam', 'Jill']; // prefer export const heroesUrl = 'api/heroes'; // prefer export const VILLAINS_URL = 'api/villains'; // tolerate
由于:
1) TypeScript 指导原则不建议使用 “I” 前缀。
2) 单独一个类的代码量小于类+接口。
3) 类能够做为接口使用(只是用 implements 代替 extends 而已)。
4) 在 Angular 依赖注入系统中,接口类(译注:指写成类的形式,可是只当作接口使用)能够做为服务提供商的查找令牌。
import { Injectable } from '@angular/core'; import { Hero } from './hero.model'; @Injectable() export class HeroCollectorService { hero: Hero; constructor() { } }
由于:
1) 遵循传统属性和方法的命名约定。
2) JavaScript 不支持真正的私有属性和方法。
3) TypeScript 工具让识别私有或公有属性和方法变得很简单。
import { Injectable } from '@angular/core'; @Injectable() export class ToastService { message: string; private toastCount: number; hide() { this.toastCount--; this.log(); } show() { this.toastCount++; this.log(); } private log() { console.log(this.message); } }
由于:
1) 空行可让阅读和定位本地导入更加容易。
2) 按字母顺序排列可让阅读和定位本地导入更加容易。
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ExceptionService, SpinnerService, ToastService } from '../../core'; import { Hero } from './hero.model';
对于函数定义以及比较复杂的逻辑,要写必要的注释。对于函数定义的注释以及函数内部的连续多行注释使用块注释“/*…*/”,对于函数内部的单行注释使用行注释“//…”。
循环内部引用的对象,若是层级很深,要在循环外部定义在循环内部直接使用的层级变量,以便提升JS引擎对循环内的标识符解析速度。好比有以下对象:
const fruit = { name: 'Apple', color: 'red', provider: { name: 'Jaffray', phones: [ '01088888888', '18812345678' ] } }; let dummy; //方法一,效率较低 for(let phone of fruit.provider.phones) { dummy = phone; } //方法二,效率较高 const phones = fruit.provider.phones; for(let phone of phones) { dummy = phone; }
经测试发现,方法二比方法一少用40%的时间。在代码量大的系统,代码的执行效率对整个系统性能的影响很是大。
深圳ICT项目中有部分代码中循环中的代码做用域链有待优化:
对于一些性质类似且同一时期会并发访问的http请求,应与接口开发者沟通,将接口合并,以减小发送请求次数、加快并发请求执行,进而提升性能。
好比分别获取性别和年龄的请求,合并在一个接口完成更高效;获取省份和市区的请求,合并在一个接口完成更高效。
在构建组件的过程当中,要将业务逻辑从组件的渲染中分离出来,组件只管对指定格式的数据进行渲染,程序根据业务须要,建立不一样的服务来完成组件须要的数据的获取和组装等处理,最终将处理好的数据传递给组件去渲染,以提升组件的可复用性能和可移植性能。
5、 应用程序结构与 NgModule
全部应用程序的源代码都放到名叫 src 的目录里。 全部特性区都在本身的文件夹中,带有它们本身的 NgModule。
全部内容都遵循每一个文件一个特性的原则。每一个组件、服务和管道都在本身的文件里。全部第三方程序包保存到其它目录里,而不是 src 目录,由于你几乎不会修改它们,因此不但愿它们弄乱你的应用程序。使用本规范介绍的文件命名约定。
由于:
1) LIFT 提供了一致的结构,它具备扩展性强、模块化的特性。由于容易快速锁定代码,提升了开发者的效率。 另外,检查应用结构是否合理的方法是问问本身:我能快速打开与此特性有关的全部文件并开始工做吗?
由于:
1) 要想高效的工做,就必须能迅速找到文件,特别是当不知道(或不记得)文件名时。 把相关的文件一块儿放在一个直观的位置能够节省时间。 富有描述性的目录结构会让你和后面的维护者眼前一亮。
由于:
1) 花费更少的时间来查找和琢磨代码,就会变得更有效率。 较长的文件名远胜于较短却容易混淆的缩写名。
2) 当你有一组小型、紧密相关的特性时,违反一物一文件的规则可能会更好, 这种状况下单一文件可能会比多个文件更容易发现和理解。注意这个例外。
由于:
1) 没人想要在超过七层的目录中查找文件。扁平的结构有利于搜索。
2) 另外一方面,心理学家们相信, 当关注的事物超过 9 个时,人类就会开始感到吃力。 因此,当一个文件夹中的文件有 10 个或更多个文件时,可能就是建立子目录的时候了。
3) 仍是根据你本身的温馨度而定吧。 除非建立新文件夹能有显著的价值,不然尽可能使用扁平结构。
由于:
1) 虽然 DRY 很重要,但若是要以牺牲 LIFT 的其它原则为代价,那就不值得了。 这也就是为何它被称为 T-DRY。 例如,把组件命名为 hero-view.component.html 是多余的,由于带有 .html 扩展名的文件显然就是一个视图 (view)。 但若是它不那么显著,或不符合常规,就把它写出来。
由于:
1) 在早期阶段可以帮助保持应用的结构小巧且易于维护和移植,这样当应用增加时就容易进化了。
2) 组件一般有四个文件 (*.html、 *.css、 *.ts 和 *.spec.ts),它们很容易把一个目录弄乱。
由于:
1) 开发人员能够快速定位代码,扫一眼就能知道每一个文件表明什么,目录尽量保持扁平,既没有重复也没有多余的名字。
2) LIFT 原则中包含了全部这些。
3) 遵循 LIFT 原则精心组织内容,避免应用变得杂乱无章。
4) 当有不少文件时(例如 10 个以上),在专用目录型结构中定位它们会比在扁平结构中更容易。
由于:
1) NgModule 使惰性加载可路由的特性变得更容易。
2) NgModule 隔离、测试和复用特性更容易。
由于:
1) 每一个应用都至少须要一个根 NgModule。
由于:
1) 能让定位和识别根模块变得更容易。
app/app.module.ts:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; @NgModule({ imports: [ BrowserModule, ], declarations: [ AppComponent, HeroesComponent ], exports: [ AppComponent ], entryComponents: [ AppComponent ] }) export class AppModule {}
由于:
1) 特性模块能够对其它模块暴露或隐藏本身的实现。
2) 特性模块标记出组成该特性分区的相关组件集合。
3) 方便路由到特性模块 —— 不管是用主动加载仍是惰性加载的方式。
4) 特性模块在特定的功能和其它应用特性之间定义了清晰的边界。
5) 特性模块帮助澄清开发职责,以便于把这些职责指派给不一样的项目组。
6) 特性模块易于隔离,以便测试。
由于:
1) SharedModule 中包含的组件、指令和管道可能须要来自其它公共模块的特性(例如来自 CommonModule 中的 ngFor 指令)。
由于:
1) SharedModule 的存在,能让经常使用的组件、指令和管道在不少其它模块的组件模板中都自动可用。
由于:
1) 惰性加载的特性模块若是导入了这个共享模块,会建立一份本身的服务副本,这可能会致使意料以外的后果。
2) 对于单例服务,你不但愿每一个模块都有本身的实例。 而若是 SharedModule 提供了一个服务,那就有可能发生这种状况。
由于:
1) CoreModule 提供了一个或多个单例服务。Angular 使用应用的根注入器注册这些服务提供商,让每一个服务的这个单例对象对全部须要它们的组件都是可用的,而不用管该组件是经过主动加载仍是惰性加载的方式加载的。
2) CoreModule 将包含一些单例服务。而若是是由惰性加载模块来导入这些服务,它就会获得一个新实例,而不是所指望的全应用级单例。
由于:
1) 真实世界中的应用会有不少只用一次的组件(例如加载动画、消息浮层、模态框等),它们只会在 AppComponent 的模板中出现。 不会在其它地方导入它们,因此没有共享的价值。 然而它们又太大了,放在根目录中就会显得乱七八糟的。
由于:
1) 若是惰性加载的特性模块直接导入 CoreModule,就会建立它本身的服务副本,并致使意料以外的后果。
2) 主动加载的特性模块已经准备好了访问 AppModule 的注入器,所以也能取得 CoreModule 中的服务。
由于:
1) CoreModule 的存在就让经常使用的单例服务在全部其它模块中可用。
2) 你但愿整个应用都使用这个单例服务。 你不但愿每一个模块都有这个单例服务的单独的实例。 然而,若是 CoreModule 中提供了一个服务,就可能偶尔致使这种后果。
AppModule 变得更小了,由于不少应用根部的类都被移到了其它模块中。 AppModule 变得稳定了,由于你将会往其它模块中添加特性组件和服务提供者,而不是这个 AppModule。 AppModule 把工做委托给了导入的模块,而不是亲力亲为。 AppModule 聚焦在它本身的主要任务上:做为整个应用的总指挥。
由于:
1) Guards能够阻止对 CoreModule 的屡次导入。
2) Guards会禁止建立单例服务的多个实例。
app/core/module-import-guard.ts:
export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) { if (parentModule) { throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`); } }
app/core/core.module.ts:
import { NgModule, Optional, SkipSelf } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoggerService } from './logger.service'; import { NavComponent } from './nav/nav.component'; import { throwIfAlreadyLoaded } from './module-import-guard'; @NgModule({ imports: [ CommonModule // we use ngFor ], exports: [NavComponent], declarations: [NavComponent], providers: [LoggerService] }) export class CoreModule { constructor( @Optional() @SkipSelf() parentModule: CoreModule) { throwIfAlreadyLoaded(parentModule, 'CoreModule'); } }
由于:
1) 这种目录让标识和隔离这些特性内容变得更轻松。
由于:
1) 直接导入并使用此模块会当即加载它,而本来的设计意图是按需加载它。
6、 Components
由于:
1) 组件有不少包含 HTML 以及可选 Angular 模板语法的模板。 它们显示内容。开发人员会把组件像原生 HTML 元素和 WebComponents 同样放进页面中。
2) 查看组件模板的 HTML 时,更容易识别一个符号是组件仍是指令。
少数状况下,你要为组件使用属性选择器,好比你要增强某个内置元素时。 好比,Material Design 组件库就会对 <button mat-button> 使用这项技术。不过,你不该该在自定义组件上使用这项技术。
app/heroes/hero-button/hero-button.component.ts:
@Component({ selector: '[tohHeroButton]', templateUrl: './hero-button.component.html' }) export class HeroButtonComponent {}
app/app.component.html:
<div tohHeroButton></div>
app/heroes/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', templateUrl: './hero-button.component.html' }) export class HeroButtonComponent {}
app/app.component.html:
<toh-hero-button></toh-hero-button>
由于:
1) 巨大的、内联的模板和样式表会遮盖组件的意图和实现方式,削弱可读性和可维护性。
2) 在多数编辑器中,编写内联的模板和样式表时都没法使用语法提示和代码片断功能。 Angular 的 TypeScript 语言服务(即将到来)能够帮助那些编辑器在编写 HTML 模板时克服这一缺陷,但对 CSS 样式没有帮助。
3) 当你移动组件文件时,相对于组件的 URL 不须要修改,由于这些文件始终会在一块儿。
4) “./ ” 前缀是相对 URL 的标准语法,没必要依赖 Angular 的特殊处理,若是没有前缀则不行。
由于:
1) 易于在类里面识别哪些属性是输入属性或输出属性。
2) 若是须要重命名与 @Input 或者 @Output 关联的属性或事件名,你能够在一个位置修改。
3) 依附到指令的元数据声明会比较简短,更易于阅读。
4) 把装饰器放到同一行能够精简代码,同时更易于识别输入或输出属性。
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button></button>`, inputs: [ 'label' ], outputs: [ 'change' ] }) export class HeroButtonComponent { change = new EventEmitter<any>(); label: string; }
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output() change = new EventEmitter<any>(); @Input() label: string; }
由于:
1) 同一个属性有两个名字(一个对内一个对外)很容易致使混淆。
2) 若是指令名也同时用做输入属性,并且指令名没法准确描述这个属性的用途时,应该使用别名。
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { // Pointless aliases @Output('changeEvent') change = new EventEmitter<any>(); @Input('labelAttribute') label: string; }
app/app.component.html:
<toh-hero-button labelAttribute="OK" (changeEvent)="doSomething()"> </toh-hero-button>
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { // No aliases @Output() change = new EventEmitter<any>(); @Input() label: string; }
app/heroes/shared/hero-button/hero-highlight.directive.ts
import { Directive, ElementRef, Input, OnChanges } from '@angular/core'; @Directive({ selector: '[heroHighlight]' }) export class HeroHighlightDirective implements OnChanges { // Aliased because `color` is a better property name than `heroHighlight` @Input('heroHighlight') color: string; constructor(private el: ElementRef) {} ngOnChanges() { this.el.nativeElement.style.backgroundColor = this.color || 'yellow'; } }
app/app.component.html:
<toh-hero-button label="OK" (change)="doSomething()"> </toh-hero-button> <!-- `heroHighlight` is both the directive name and the data-bound aliased property name --> <h3 heroHighlight="skyblue">The Great Bombasto</h3>
由于:
1) 把类的成员按照统一的顺序排列,易于阅读,能当即识别出组件的哪一个成员服务于何种目的。
app/shared/toast/toast.component.ts:
export class ToastComponent implements OnInit { private defaults = { title: '', message: 'May the Force be with you' }; message: string; title: string; private toastElement: any; ngOnInit() { this.toastElement = document.getElementById('toh-toast'); } // private methods private hide() { this.toastElement.style.opacity = 0; window.setTimeout(() => this.toastElement.style.zIndex = 0, 400); } activate(message = this.defaults.message, title = this.defaults.title) { this.title = title; this.message = message; this.show(); } private show() { console.log(this.message); this.toastElement.style.opacity = 1; this.toastElement.style.zIndex = 9999; window.setTimeout(() => this.hide(), 2500); } }
app/shared/toast/toast.component.ts:
export class ToastComponent implements OnInit { // public properties message: string; title: string; // private fields private defaults = { title: '', message: 'May the Force be with you' }; private toastElement: any; // public methods activate(message = this.defaults.message, title = this.defaults.title) { this.title = title; this.message = message; this.show(); } ngOnInit() { this.toastElement = document.getElementById('toh-toast'); } // private methods private hide() { this.toastElement.style.opacity = 0; window.setTimeout(() => this.toastElement.style.zIndex = 0, 400); } private show() { console.log(this.message); this.toastElement.style.opacity = 1; this.toastElement.style.zIndex = 9999; window.setTimeout(() => this.hide(), 2500); } }
由于:
1) 当逻辑被放置到服务里,并以函数的形式暴露时,能够被多个组件重复使用。
2) 在单元测试时,服务里的逻辑更容易被隔离。当组件中调用逻辑时,也很容易被模拟。
3) 从组件移除依赖并隐藏实施细节。
4) 保持组件苗条、精简和聚焦。
由于:
1) 与内置事件命名一致,例如按钮点击。
2) Angular 容许另外一种备选语法 on-*。若是事件的名字自己带有前缀 on,那么绑定的表达式多是 on-onEvent。
app/heroes/hero.component.ts:
@Component({ selector: 'toh-hero', template: `...` }) export class HeroComponent { @Output() onSavedTheDay = new EventEmitter<boolean>(); }
app/app.component.html:
<toh-hero (onSavedTheDay)="onSavedTheDay($event)"></toh-hero>
app/heroes/hero.component.ts:
export class HeroComponent { @Output() savedTheDay = new EventEmitter<boolean>(); }
app/app.component.html:
<toh-hero (savedTheDay)="onSavedTheDay($event)"></toh-hero>
由于:
1) 逻辑应该只出如今一个地方(组件类里)而不该分散在两个地方。
2) 将组件的表现层逻辑放到组件类而非模板里,能够加强测试性、维护性和重复使用性。
app/heroes/hero-list/hero-list.component.ts:
@Component({ selector: 'toh-hero-list', template: ` <section> Our list of heroes: <hero-profile *ngFor="let hero of heroes" [hero]="hero"> </hero-profile> Total powers: {{totalPowers}}<br> Average power: {{totalPowers / heroes.length}} </section> ` }) export class HeroListComponent { heroes: Hero[]; totalPowers: number; }
app/heroes/hero-list/hero-list.component.ts:
@Component({ selector: 'toh-hero-list', template: ` <section> Our list of heroes: <toh-hero *ngFor="let hero of heroes" [hero]="hero"> </toh-hero> Total powers: {{totalPowers}}<br> Average power: {{avgPower}} </section> ` }) export class HeroListComponent { heroes: Hero[]; totalPowers: number; get avgPower() { return this.totalPowers / this.heroes.length; } }
7、 指令
由于:
1) 属性型指令没有模板。
2) 一个元素可使用多个属性型指令。
app/shared/highlight.directive.ts:
@Directive({ selector: '[tohHighlight]' }) export class HighlightDirective { @HostListener('mouseover') onMouseEnter() { // do highlight work } }
app/app.component.html:
<div tohHighlight>Bombasta</div>
由于:
1) 对于关联到 @HostBinding 的属性或关联到 @HostListener 的方法,要修改时,只需在指令类中的一个地方修改。 若是使用元数据属性 host,你就得在组件类中修改属性声明的同时修改相关的元数据。
app/shared/validator.directive.ts:
import { Directive, HostBinding, HostListener } from '@angular/core'; @Directive({ selector: '[tohValidator]' }) export class ValidatorDirective { @HostBinding('attr.role') role = 'button'; @HostListener('mouseenter') onMouseEnter() { // do work } }
import { Directive } from '@angular/core'; @Directive({ selector: '[tohValidator2]', host: { '[attr.role]': 'role', '(mouseenter)': 'onMouseEnter()' } }) export class Validator2Directive { role = 'button'; onMouseEnter() { // do work } }
8、 服务
由于:
1) 服务是在特性范围或应用内共享方法的理想载体。
2) 服务是共享状态性内存数据的理想载体。
app/heroes/shared/hero.service.ts:
export class HeroService { constructor(private http: Http) { } getHeroes() { return this.http.get('api/heroes').pipe( map((response: Response) => <Hero[]>response.json())); } }
由于:
1) 当服务有多个职责时,它很难被测试。
2) 当某个服务有多个职责时,每一个注入它的组件或服务都会承担这些职责的所有开销。
由于:
1) Angular 注入器是层次化的。
2) 当你在根注入器上提供该服务时,该服务实例在每一个须要该服务的类中是共享的。当服务要共享方法或状态时,这是最理想的选择。
3) 当你在服务的 @Injectable 中注册服务时,Angular CLI 生产环境构建时使用的优化工具能够进行摇树优化,从而移除那些你的应用中从未用过的服务。
4) 当不一样的两个组件须要一个服务的不一样的实例时,上面的方法这就不理想了。在这种状况下,对于须要崭新和单独服务实例的组件,最好在组件级提供服务。
src/app/treeshaking/service.ts:
@Injectable({ providedIn: 'root', }) export class Service { }
由于:
1) Angular 的 DI 机制会根据服务的构造函数参数的声明类型来解析服务的全部依赖。
2) 当服务只接受类型令牌相关的依赖时,比起在每一个构造函数参数上使用 @Inject(),@Injectable() 的语法简洁多了。
app/heroes/shared/hero-arena.service.ts:
export class HeroArena { constructor( @Inject(HeroService) private heroService: HeroService, @Inject(Http) private http: Http) {} }
app/heroes/shared/hero-arena.service.ts:
@Injectable() export class HeroArena { constructor( private heroService: HeroService, private http: Http) {} }
9、 数据服务
由于:
1) 组件的职责是为视图展现或收集信息。它不该该关心如何获取数据,它只须要知道向谁请求数据。把如何获取数据的逻辑移动到数据服务里,简化了组件,让其聚焦于视图。
2) 在测试使用数据服务的组件时,可让数据调用更容易被测试(模拟或者真实)。
3) 数据管理的详情,好比头信息、方法、缓存、错误处理和重试逻辑,不是组件和其它的数据消费者应该关心的事情。
4) 数据服务应该封装这些细节。这样,在服务内部修改细节,就不会影响到它的消费者。而且更容易经过实现一个模拟服务来对消费者进行测试。
10、 生命周期钩子
由于:
1) 若是使用强类型的方法签名,编译器和编辑器能够帮你揪出拼写错误。
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button>OK<button>` }) export class HeroButtonComponent { onInit() { // misspelled console.log('The component is initialized'); } }
app/heroes/shared/hero-button/hero-button.component.ts:
@Component({ selector: 'toh-hero-button', template: `<button>OK</button>` }) export class HeroButtonComponent implements OnInit { ngOnInit() { console.log('The component is initialized'); } }