风格指南

Welcome to the Angular Style Guide

欢迎光临 Angular 风格指南

Purpose

目的

Looking for an opinionated guide to Angular syntax, conventions, and application structure? Step right in! This style guide presents our preferred conventions and, as importantly, explains why.

如果你正在寻找关于 Angular 语法、约定和应用组织结构的官方指南,那你就来对了。 本风格指南介绍了提倡的约定,更重要的是,解释了为什么。

Style Vocabulary

风格词汇

Each guideline describes either a good or bad practice, and all have a consistent presentation.

每个指导原则都会描述好的或者坏的做法,所有指导原则风格一致。

The wording of each guideline indicates how strong the recommendation is.

指导原则中使用的词汇表明推荐的程度。

Do is one that should always be followed. Always might be a bit too strong of a word. Guidelines that literally should always be followed are extremely rare. On the other hand, you need a really unusual case for breaking a Do guideline.

坚持意味着总是应该遵循的约定。 总是可能有点太强了。应该总是遵循的指导原则非常少。 但是,只有遇到非常不寻常的情况才能打破坚持的原则。

Consider guidelines should generally be followed.

考虑标志着通常应该遵循的指导原则。

If you fully understand the meaning behind the guideline and have a good reason to deviate, then do so. Please strive to be consistent.

如果能完全理解指导原则背后的含义,并且很好的理由背离它,那就可以那么做。但是请保持一致。

Avoid indicates something you should almost never do. Code examples to avoid have an unmistakeable red header.

避免标志着我们决不应该做的事。需要避免的代码范例会有明显的红色标题。

File Structure Conventions

文件结构约定

Some code examples display a file that has one or more similarly named companion files. (e.g. hero.component.ts and hero.component.html).

在一些代码例子中,有的文件有一个或多个相似名字的伴随文件。(例如 hero.component.ts 和 hero.component.html)。

The guideline will use the shortcut hero.component.ts|html|css|spec to represent those various files. Using this shortcut makes this guide's file structures easier to read and more terse.

本指南将会使用像hero.component.ts|html|css|spec的简写来表示上面描述的多个文件,目的是保持本指南的简洁性,增加描述文件结构时的可读性。

Table of Contents

目录

  1. Single Responsibility

    单一职责

  2. Naming

    命名

  3. Coding Conventions

    代码约定

  4. App Structure and Angular Modules

    应用结构与 Angular 模块

  5. Components

    组件

  6. Directives

    指令

  7. Services

    服务

  8. Data Services

    数据服务

  9. Lifecycle Hooks

    生命周期钩子

  10. Appendix

    附录

Single Responsibility

单一职责

Apply the Single Responsibility Principle to all components, services, and other symbols. This helps make the app cleaner, easier to read and maintain, and more testable.

所有组件、服务和其它符号都要遵循单一职责原则。 这会使应用程序更干净,易于阅读和维护,提高可测试性。

Rule of One

单一法则

Style 01-01

风格 01-01

Do define one thing (e.g. service or component) per file.

坚持每个文件只定义一样东西(例如服务或组件)。

Consider limiting files to 400 lines of code.

考虑把文件大小限制在 400 行代码以内。

Why? One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.

为何?单组件文件非常容易阅读、维护,并能防止在版本控制系统里与团队冲突。

Why? One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

为何?单组件文件可以防止一些隐蔽的程序缺陷,当把多个组件合写在同一个文件中时,可能造成共享变量、创建意外的闭包,或者与依赖之间产生意外耦合等情况。

Why? A single component can be the default export for its file which facilitates lazy loading with the Router.

为何?单独的组件通常是该文件默认的导出,可以用路由器实现按需加载。

The key is to make the code more reusable, easier to read, and less mistake prone.

最关键的是,可以增强代码可重用性和阅读性,减少出错的可能性。

The following negative example defines the AppComponent, bootstraps the app, defines the Hero model object, and loads heroes from the server ... all in the same file. Don't do this.

下面的负面例子定义了AppComponent,它来引导应用程序,定义了Hero模型对象,并从服务器加载了英雄 ... 所有都在同一个文件。 不要这么做

app/heroes/hero.component.ts

/* avoid */ import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { BrowserModule } from '@angular/platform-browser'; import { NgModule, Component, OnInit } from '@angular/core'; class Hero { id: number; name: string; } @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <pre>{{heroes | json}}</pre> `, styleUrls: ['app/app.component.css'] }) class AppComponent implements OnInit { title = 'Tour of Heroes'; heroes: Hero[] = []; ngOnInit() { getHeroes().then(heroes => this.heroes = heroes); } } @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule); const HEROES: Hero[] = [ {id: 1, name: 'Bombasto'}, {id: 2, name: 'Tornado'}, {id: 3, name: 'Magneta'}, ]; function getHeroes(): Promise<Hero[]> { return Promise.resolve(HEROES); // TODO: get hero data from the server; }

Better to redistribute the component and supporting activities into their own dedicated files.

最好将组件及其支撑部件重新分配到独立的文件。

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule); import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; @NgModule({ imports: [ BrowserModule, ], declarations: [ AppComponent, HeroesComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } import { Component } from '@angular/core'; import { HeroService } from './heroes'; @Component({ moduleId: module.id, selector: 'toh-app', template: ` <toh-heroes></toh-heroes> `, styleUrls: ['app.component.css'], providers: [ HeroService ] }) export class AppComponent { } import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from './shared'; @Component({ selector: 'toh-heroes', template: ` <pre>{{heroes | json}}</pre> ` }) export class HeroesComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.heroService.getHeroes() .then(heroes => this.heroes = heroes); } } import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { getHeroes() { return Promise.resolve(HEROES); } } export class Hero { id: number; name: string; } import { Hero } from './hero.model'; export const HEROES: Hero[] = [ {id: 1, name: 'Bombasto'}, {id: 2, name: 'Tornado'}, {id: 3, name: 'Magneta'}, ];

As the app grows, this rule becomes even more important.

随着应用程序的成长,本法则会变得越来越重要。

Back to top回到顶部

Small Functions

简单函数

Style 01-02

风格 01-02

Do define small functions

坚持定义简单函数

Consider limiting to no more than 75 lines.

考虑限制在 75 行之内。

Why? Small functions are easier to test, especially when they do one thing and serve one purpose.

为何?简单函数更易于测试,特别是当它们只做一件事,只为一个目的服务时。

Why? Small functions promote reuse.

为何?简单函数促进代码重用。

Why? Small functions are easier to read.

为何?简单函数更易于阅读。

Why? Small functions are easier to maintain.

为何?简单函数更易于维护。

Why? Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.

为何?简单函数可避免易在大函数中产生的隐蔽性错误,例如与外界共享变量、创建意外的闭包或与依赖之间产生意外耦合等。

Back to top回到顶部

Naming

命名

Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.

命名约定对可维护性和可读性非常重要。本指南为文件名和符号名推荐了一套命名约定。

General Naming Guidelines

总体命名指导原则

Style 02-01

风格 02-01

Do use consistent names for all symbols.

坚持所有符号使用一致的命名规则。

Do follow a pattern that describes the symbol's feature then its type. The recommended pattern is feature.type.ts.

坚持遵循同一个模式来描述符号的特性和类型。推荐的模式为feature.type.ts

Why? Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency.

为何?命名约定提供了一致的方式来查找内容,让我们一眼就能锁定。 项目的一致性是至关重要的。团队内的一致性也很重要。整个公司的一致性会提供惊人的效率。

Why? The naming conventions should simply help find desited code faster and make it easier to understand.

为何?命名约定帮助我们更快得找到不在手头的代码,更容易理解它。

Why? Names of folders and files should clearly convey their intent. For example, app/heroes/hero-list.component.ts may contain a component that manages a list of heroes.

为何?目录名和文件名应该清楚的传递它们的意图。 例如,app/heroes/hero-list.component.ts包含了一个用来管理英雄列表的组件。

Back to top回到顶部

Separate File Names with Dots and Dashes

使用点和横杠来分隔文件名

Style 02-02

风格 02-02

Do use dashes to separate words in the descriptive name.

坚持 在描述性名字中,用横杠来分隔单词。

Do use dots to separate the descriptive name from the type.

坚持使用点来分隔描述性名字和类型。

Do use consistent type names for all components following a pattern that describes the component's feature then its type. A recommended pattern is feature.type.ts.

坚持遵循先描述组件特性,再描述它的类型的模式,对所有组件使用一致的类型命名规则。推荐的模式为feature.type.ts

Do use conventional type names including .service, .component, .pipe, .module, .directive. Invent additional type names if you must but take care not to create too many.

坚持使用惯用的后缀来描述类型,包括*.service*.component*.pipe.module.directive。 必要时可以创建更多类型名,但必须注意,不要创建太多。

Why? Type names provide a consistent way to quickly identify what is in the file.

为何?类型名字提供一致的方式来快速的识别文件中有什么。

Why? Make it easy to find a specific file type using an editor or IDE's fuzzy search techniques.

为何? 利用编辑器或者 IDE 的模糊搜索功能,可以很容易地找到特定文件。

Why? Unabbreviated type names such as .service are descriptive and unambiguous. Abbreviations such as .srv, .svc, and .serv can be confusing.

为何?.service这样的没有简写过的类型名字,描述清楚,毫不含糊。 像.srv, .svc, 和 .serv这样的简写可能令人困惑。

Why? Provides pattern matching for any automated tasks.

为何?为自动化任务提供模式匹配。

Back to top回到顶部

Symbols and File Names

符号名与文件名

Style 02-03

风格 02-03

Do use consistent names for all assets named after what they represent.

坚持为所有东西使用一致的命名约定,以它们所代表的东西命名。

Do use upper camel case for class names. Match the name of the symbol to the name of the file.

坚持使用大写驼峰命名法来命名类。符号名匹配它所在的文件名。

Do append the symbol name with the conventional suffix for a thing of that type (e.g., Component, Directive, Module, Pipe, Service).

坚持在符号名后面追加约定的类型后缀(例如ComponentDirectiveModulePipeService)。

Do give the filename the conventional suffix for a file of that type (e.g., .component.ts, .directive.ts, .module.ts, .pipe.ts, .service.ts).

坚持在文件名后面追加约定的类型后缀(例如.component.ts.directive.ts.module.ts.pipe.ts.service.ts)。

Why? Provides a consistent way to quickly identify and reference assets.

为何?提供一致的方式来快速标识和引用资产。

Why? Upper camel case is conventional for identifying objects that can be instantiated using a constructor.

为何?大驼峰命名法用于标识可以通过构造函数实例化的对象。

Symbol Name

符号名

File Name

文件名

@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

Back to top回到顶部

Service Names

服务名

Style 02-04

风格 02-04

Do use consistent names for all services named after their feature.

坚持使用一致的规则命名服务,以它们的特性来命名。

Do use upper camel case for services.

坚持使用大写驼峰命名法命名服务。

Do suffix services with Service when it is not clear what they are (e.g. when they are nouns).

坚持添加Service后缀,当不清楚它们是什么时(例如当它们是名词时)。

Why? Provides a consistent way to quickly identify and reference services.

为何?提供一致的方式来快速识别和引用服务。

Why? Clear service names such as Logger do not require a suffix.

为何?Logger这样的清楚的服务名不需要后缀。

Why? Service names such as Credit are nouns and require a suffix and should be named with a suffix when it is not obvious if it is a service or something else.

为何?Credit这样的,服务名是名词,需要一个后缀。当不能明显分辨它是服务还是其它东西时,应该添加后缀。

Symbol Name

符号名

File Name

文件名

@Injectable() export class HeroDataService { }

hero-data.service.ts

@Injectable() export class CreditService { }

credit.service.ts

@Injectable() export class Logger { }

logger.service.ts

Back to top回到顶部

Bootstrapping

引导

Style 02-05

风格 02-05

Do put bootstrapping and platform logic for the app in a file named main.ts.

坚持把应用的引导程序和平台相关的逻辑放到名为main.ts的文件里。

Do include error handling in the bootstrapping logic.

坚持在引导逻辑中包含错误处理代码。

Avoid putting app logic in the main.ts. Instead consider placing it in a component or service.

避免把应用逻辑放在main.ts中,而应放在组件或服务里。

Why? Follows a consistent convention for the startup logic of an app.

为何?应用的启动逻辑遵循一致的约定。

Why? Follows a familiar convention from other technology platforms.

为何?这是从其它技术平台借鉴的常用约定。

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .then(success => console.log(`Bootstrap success`)) .catch(err => console.error(err));
Back to top回到顶部

Directive Selectors

指令选择器

Style 02-06

风格 02-06

Do Use lower camel case for naming the selectors of directives.

坚持使用小驼峰命名法来命名指令的选择器。

Why? Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.

为何?保持指令中定义的属性名与绑定的视图 HTML 属性名字一致。

Why? The Angular HTML parser is case sensitive and will recognize lower camel case.

为何?Angular HTML 解析器是大小写敏感的,它识别小写驼峰写法。

Back to top回到顶部

Custom Prefix for Components

为组件添加自定义前缀

Style 02-07

风格 02-07

Do use a hyphenated, lowercase element selector value (e.g. admin-users).

坚持使用带连字符的小写元素选择器值(例如admin-users)。

Do use a custom prefix for a component selector. For example, the prefix toh represents from Tour of Heroes and the prefix admin represents an admin feature area.

坚持为组件选择器添加自定义前缀。 例如,toh前缀表示 Tour of Heroes(英雄指南),而前缀`admin表示管理特性区。

Do use a prefix that identifies the feature area or the app itself.

坚持使用前缀来识别特性区或者应用程序本身。

Why? Prevents element name collisions with components in other apps and with native HTML elements.

为何?防止与其它应用中的组件和原生 HTML 元素发生命名冲突。

Why? Makes it easier to promote and share the component in other apps.

为何?更容易在其它应用中推广和共享组件。

Why? Components are easy to identify in the DOM.

为何?组件在 DOM 中更容易被区分出来。

app/heroes/hero.component.ts

/* avoid */ // HeroComponent is in the Tour of Heroes feature @Component({ selector: 'hero' }) export class HeroComponent {}

app/users/users.component.ts

/* avoid */ // UsersComponent is in an Admin feature @Component({ selector: 'users' }) export class UsersComponent {}

app/heroes/hero.component.ts

@Component({ selector: 'toh-hero' }) export class HeroComponent {}

app/users/users.component.ts

@Component({ selector: 'admin-users' }) export class UsersComponent {}

Custom Prefix for Directives

为指令添加自定义前缀

Style 02-08

风格 02-08

Do use a custom prefix for the selector of directives (e.g, the prefix toh from Tour of Heroes).

坚持为指令的选择器添加自定义前缀(例如前缀toh来自Tour of Heroes)。

Do spell non-element selectors in lower camel case unless the selector is meant to match a native HTML attribute.

坚持用小驼峰形式拼写非元素选择器,除非该选择器用于匹配原生 HTML 属性。

Why? Prevents name collisions.

为何?防止名字冲突。

Why? Directives are easily identified.

为何?指令更加容易被识别。

app/shared/validate.directive.ts

/* avoid */ @Directive({ selector: '[validate]' }) export class ValidateDirective {}

app/shared/validate.directive.ts

@Directive({ selector: '[tohValidate]' }) export class ValidateDirective {}
Back to top回到顶部

Pipe Names

管道名

Style 02-09

风格 02-09

Do use consistent names for all pipes, named after their feature.

坚持为所有管道使用一致的命名约定,用它们的特性来命名。

Why? Provides a consistent way to quickly identify and reference pipes.

为何?提供一致方式快速识别和引用管道。

Symbol Name

符号名

File Name

文件名

@Pipe({ name: 'ellipsis' }) export class EllipsisPipe implements PipeTransform { }

ellipsis.pipe.ts

@Pipe({ name: 'initCaps' }) export class InitCapsPipe implements PipeTransform { }

init-caps.pipe.ts

Back to top回到顶部

Unit Test File Names

单元测试文件名

Style 02-10

风格 02-10

Do name test specification files the same as the component they test.

坚持测试规格文件名与被测试组件文件名相同。

Do name test specification files with a suffix of .spec.

坚持测试规格文件名添加.spec后缀。

Why? Provides a consistent way to quickly identify tests.

为何?提供一致的方式来快速识别测试。

Why? Provides pattern matching for karma or other test runners.

为何?提供一个与 karma 或者其它测试运行器相配的命名模式。

Symbol Name

符号名

File Name

文件名

Components

组件

heroes.component.spec.ts

hero-list.component.spec.ts

hero-detail.component.spec.ts

Services

服务

logger.service.spec.ts

hero.service.spec.ts

filter-text.service.spec.ts

Pipes

管道

ellipsis.pipe.spec.ts

init-caps.pipe.spec.ts

Back to top回到顶部

End to End Test File Names

端到端测试文件名

Style 02-11

风格 02-11

Do name end-to-end test specification files after the feature they test with a suffix of .e2e-spec.

坚持端到端测试规格文件和它们所测试的特性同名,添加.e2e-spec后缀。

Why? Provides a consistent way to quickly identify end-to-end tests.

为何?提供一致的方式快速识别端到端测试文件。

Why? Provides pattern matching for test runners and build automation.

为何?提供一个与测试运行器和构建自动化匹配的模式。

Symbol Name

符号名

File Name

文件名

End to End Tests

端到端测试

app.e2e-spec.ts

heroes.e2e-spec.ts

Back to top回到顶部

Angular NgModule Names

Angular NgModule 命名

Style 02-12

风格 02-12

Do append the symbol name with the suffix Module.

坚持为符号名添加Module后缀

Do give the file name the .module.ts extension.

坚持为文件名添加.module.ts扩展名。

Do name the module after the feature and folder it resides in.

坚持用特性名和所在目录命名模块。

Why? Provides a consistent way to quickly identify and reference modules.

为何?提供一致的方式来快速标识和引用模块。

Why? Upper camel case is conventional for identifying objects that can be instantiated using a constructor.

为何?大驼峰命名法是一种命名约定,用来标识可用构造函数实例化的对象。

Why? Easily identifies the module as the root of the same named feature.

为何?很容易就能看出这个模块是同名特性的根模块。

Do suffix a RoutingModule class name with RoutingModule.

坚持RoutingModule 类名添加RoutingModule后缀。

Do end the filename of a RoutingModule with -routing.module.ts.

坚持RoutingModule 的文件名添加-routing.module.ts后缀。

Why? A RoutingModule is a module dedicated exclusively to configuring the Angular router. A consistent class and file name convention make these modules easy to spot and verify.

为何?RoutingModule是一种专门用来配置 Angular 路由器的模块。 “类名和文件名保持一致”的约定使这些模块易于发现和验证。

Symbol NameFile Name
@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

Back to top回到顶部

Coding Conventions

编程约定

Have consistent set of coding, naming, and whitespace conventions.

坚持一致的编程、命名和空格的约定。

Class

Style 03-01

风格 03-01

Do use upper camel case when naming classes.

坚持使用大写驼峰命名法来命名类。

Why? Follows conventional thinking for class names.

为何?遵循类命名传统约定。

Why? Classes can be instantiated and construct an instance. By convention, upper camel case indicates a constructable asset.

为何?类可以被实例化和构造实例。根据约定,用大写驼峰命名法来标识可构造的东西。

app/shared/exception.service.ts

/* avoid */ export class exceptionService { constructor() { } }

app/shared/exception.service.ts

export class ExceptionService { constructor() { } }
Back to top回到顶部

Constants

常量

Style 03-02

风格 03-02

Do declare variables with const if their values should not change during the application lifetime.

坚持const声明变量,除非它们的值在应用的生命周期内会发生变化。

Why? Conveys to readers that the value is invariant.

为何?告诉读者这个值是不可变的。

Why? TypeScript helps enforce that intent by requiring immediate initialization and by preventing subsequent re-assignment.

为何? TypeScript 会要求在声明时立即初始化,并阻止再次赋值,以确保达成我们的意图。

Consider spelling const variables in lower camel case.

考虑 把常量名拼写为小驼峰格式。

Why? lower camel case variable names (heroRoutes) are easier to read and understand than the traditional UPPER_SNAKE_CASE names (HERO_ROUTES).

为何?小驼峰变量名 (heroRoutes) 比传统的大写蛇形命名法 (HERO_ROUTES) 更容易阅读和理解。

Why? The tradition of naming constants in UPPER_SNAKE_CASE reflects an era before the modern IDEs that quickly reveal the const declaration. TypeScript itself prevents accidental reassignment.

为何? 把常量命名为大写蛇形命名法的传统源于现代 IDE 出现之前, 以便阅读时可以快速发现那些const定义。 TypeScript 本身就能够防止意外赋值。

Do tolerate existing const variables that are spelled in UPPER_SNAKE_CASE.

坚持容许现存的const常量沿用大写蛇形命名法。

Why? The tradition of UPPER_SNAKE_CASE remains popular and pervasive, especially in third party modules. It is rarely worth the effort to change them or the risk of breaking existing code and documentation.

为何?传统的大写蛇形命名法仍然很流行、很普遍,特别是在第三方模块中。 修改它们没多大价值,还会有破坏现有代码和文档的风险。

app/shared/data.service.ts

export const mockHeroes = ['Sam', 'Jill']; // prefer export const heroesUrl = 'api/heroes'; // prefer export const VILLAINS_URL = 'api/villains'; // tolerate
Back to top回到顶部

Interfaces

接口

Style 03-03

风格 03-03

Do name an interface using upper camel case.

坚持使用大写驼峰命名法来命名接口。

Consider naming an interface without an I prefix.

考虑不要在接口名字前面加I前缀。

Consider using a class instead of an interface.

考虑用类代替接口。

Why? TypeScript guidelines discourage the "I" prefix.

为何?TypeScript 指导原则不建议使用 “I” 前缀。

Why? A class alone is less code than a class-plus-interface.

为何?单独一个类的代码量小于类+接口

Why? A class can act as an interface (use implements instead of extends).

为何?类可以作为接口使用(只是用implements代替extends而已)。

Why? An interface-class can be a provider lookup token in Angular dependency injection.

为何?在 Angular 依赖注入系统中,接口类可以作为服务提供商的查找令牌。

app/shared/hero-collector.service.ts

/* avoid */ import { Injectable } from '@angular/core'; import { IHero } from './hero.model.avoid'; @Injectable() export class HeroCollectorService { hero: IHero; constructor() { } }

app/shared/hero-collector.service.ts

import { Injectable } from '@angular/core'; import { Hero } from './hero.model'; @Injectable() export class HeroCollectorService { hero: Hero; constructor() { } }
Back to top回到顶部

Properties and Methods

属性和方法

Style 03-04

样式 03-04

Do use lower camel case to name properties and methods.

坚持使用小写驼峰命名法来命名属性和方法。

Avoid prefixing private properties and methods with an underscore.

避免为私有属性和方法添加下划线前缀。

Why? Follows conventional thinking for properties and methods.

为何?遵循传统属性和方法的命名约定。

Why? JavaScript lacks a true private property or method.

为何? JavaScript 不支持真正的私有属性和方法。

Why? TypeScript tooling makes it easy to identify private vs public properties and methods.

为何? TypeScript 工具让识别私有或公有属性和方法变得很简单。

app/shared/toast.service.ts

/* avoid */ 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); } }

app/shared/toast.service.ts

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); } }
Back to top回到顶部

Import Line Spacing

导入语句中的空行

Style 03-06

风格 03-06

Consider leaving one empty line between third party imports and application imports.

坚持在第三方导入和应用导入之间留一个空行。

Consider listing import lines alphabetized by the module.

考虑按模块名字的字母顺排列导入行。

Consider listing destructured imported assets alphabetically.

考虑在解构表达式中按字母顺序排列导入的东西。

Why? The empty line makes it easy to read and locate imports.

为何?空行可以让阅读和定位本地导入更加容易。

Why? Alphabetizing makes it easier to read and locate imports.

为何?按字母顺序排列可以让阅读和定位本地导入更加容易。

app/heroes/shared/hero.service.ts

/* avoid */ import { ExceptionService, SpinnerService, ToastService } from '../../core'; import { Http, Response } from '@angular/http'; import { Injectable } from '@angular/core'; import { Hero } from './hero.model';

app/heroes/shared/hero.service.ts

import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Hero } from './hero.model'; import { ExceptionService, SpinnerService, ToastService } from '../../core';
Back to top回到顶部

App Structure and Angular Modules

应用程序结构与 Angular 模块

Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road.

准备一个近期实施方案和一个长期的愿景。从零开始,但要考虑应用程序接下来的路往哪儿走。

All of the app's code goes in a folder named app. All feature areas are in their own folder, with their own Angular module.

所有应用程序的源代码都放到名叫app的目录里。 所有特性区都在自己的文件夹中,带有它们自己的 Angular 模块。

All content is 1 asset per file. Each component, service, and pipe is in its own file. All 3rd party vendor scripts are stored in another folder and not in the app folder. You didn't write them and you don't want them cluttering app. Use the naming conventions for files in this guide.

所有内容都遵循每个文件一个特性的原则。每个组件、服务和管道都在自己的文件里。 所有第三方程序包保存到其它目录里,不是app目录。 你不会修改它们,所以不希望它们弄乱我们的应用程序。 使用本指南介绍的文件命名约定。

Back to top回到顶部

LIFT

LIFT

Style 04-01

风格 04-01

Do structure the app such that you can Locate code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to be DRY.

坚持组织应用的结构,达到这些目的:快速定位 (Locate) 代码、一眼识别 (Identify) 代码、 尽量保持扁平结构 (Flattest) 和尝试 (Try) 遵循DRY (Do Not Repeat Yourself, 不重复自己) 原则。

Do define the structure to follow these four basic guidelines, listed in order of importance.

坚持四项基本原则定义文件结构,上面的原则是按重要顺序排列的。

Why? LIFT Provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly. To confirm your intuition about a particular structure, ask: can I quickly open and start work in all of the related files for this feature?

为何?LIFT提供了一致的结构,它具有扩展性强、模块化的特性。因为容易快速锁定代码,提高了开发者的效率。 另外,检查应用结构是否合理的方法是问问自己:我们能快速打开与此特性有关的所有文件并开始工作吗?

Back to top回到顶部

Locate

定位

Style 04-02

风格04-02

Do make locating code intuitive, simple and fast.

坚持直观、简单和快速地定位代码。

Why?
To work efficiently you must be able to find files quickly, especially when you do not know (or do not remember) the file names. Keeping related files near each other in an intuitive location saves time. A descriptive folder structure makes a world of difference to you and the people who come after you.

为何? 要想高效的工作,就必须能迅速找到文件,特别是当不知道(或不记得)文件时。 把相关的文件一起放在一个直观的位置可以节省时间。 富有描述性的目录结构会让你和后面的维护者眼前一亮。

Back to top回到顶部

Identify

识别

Style 04-03

风格 04-03

Do name the file such that you instantly know what it contains and represents.

坚持命名文件到这个程度:看到名字立刻知道它包含了什么,代表了什么。

Do be descriptive with file names and keep the contents of the file to exactly one component.

坚持文件名要具有说明性,确保文件中只包含一个组件。

Avoid files with multiple components, multiple services, or a mixture.

避免创建包含多个组件、服务或者混合体的文件。

Why? Spend less time hunting and pecking for code, and become more efficient. Longer file names are far better than short-but-obscure abbreviated names.

为何?花费更少的时间来查找和琢磨代码,就会变得更有效率。 较长的文件名远胜于较短却容易混淆的缩写名。

It may be advantageous to deviate from the one-thing-per-file rule when you have a set of small, closely-related features that are better discovered and understood in a single file than as multiple files. Be wary of this loophole.

当你有一组小型、紧密相关的特性时,违反一物一文件的规则可能会更好, 这种情况下单一文件可能会比多个文件更容易发现和理解。注意这个例外。

Back to top回到顶部

Flat

扁平

Style 04-04

风格 04-04

Do keep a flat folder structure as long as possible.

坚持尽可能保持扁平的目录结构。

Consider creating sub-folders when a folder reaches seven or more files.

考虑当同一目录下达到 7 个或更多个文件时创建子目录。

Consider configuring the IDE to hide distracting, irrelevant files such as generated .js and .js.map files.

考虑配置 IDE,以隐藏无关的文件,例如生成出来的.js文件和.js.map文件等。

Why? No one wants to search for a file through seven levels of folders. A flat structure is easy to scan.

为何?没人想要在超过七层的目录中查找文件。扁平的结构有利于搜索。

On the other hand, psychologists believe that humans start to struggle when the number of adjacent interesting things exceeds nine. So when a folder has ten or more files, it may be time to create subfolders.

另一方面,心理学家们相信, 当关注的事物超过 9 个时,人类就会开始感到吃力。 所以,当一个文件夹中的文件有 10 个或更多个文件时,可能就是创建子目录的时候了。

Base your decision on your comfort level. Use a flatter structure until there is an obvious value to creating a new folder.

还是根据你自己的舒适度而定吧。 除非创建新文件夹能有显著的价值,否则尽量使用扁平结构。

Back to top回到顶部

T-DRY (Try to be DRY)

T-DRY (尝试不重复自己)

Style 04-05

风格 04-05

Do be DRY (Don't Repeat Yourself)

坚持 DRY(Don't Repeat Yourself,不重复自己)。

Avoid being so DRY that you sacrifice readability.

避免过度 DRY,以致牺牲了阅读性。

Why? Being DRY is important, but not crucial if it sacrifices the other elements of LIFT. That's why its calle T-DRY. For example, it's redundant to name a component, hero-view.component.html because a component is obviously a view. But if something is not obvious or departs from a convention, then spell it out.

为何?虽然 DRY 很重要,但如果要以牺牲 LIFT 的其它原则为代价,那就不值得了。 这也就是为什么它被称为 T-DRY。 例如,把组件命名为hero-view.component.html是多余的,因为组件显然就是一个视图 (view)。 但如果它不那么显著,或不符合常规,就把它写出来。

Back to top回到顶部

Overall Structural Guidelines

总体结构指导原则

Style 04-06

风格 04-06

Do start small but keep in mind where the app is heading down the road.

坚持从零开始,但要考虑应用程序接下来的路往哪儿走。

Do have a near term view of implementation and a long term vision.

坚持有一个近期实施方案和一个长期的愿景。

Do put all of the app's code in a folder named app.

坚持把所有源代码都放到名为app的目录里。

Consider creating a folder for a component when is has multiple accompanying files (.ts, .html, .css and .spec).

坚持如果组件具有多个伴隨文件 (.ts.html.css.spec),就为它创建一个文件夹。

Why? Helps keep the app structure small and easy to maintain in the early stages, while being easy to evolve as the app grows.

为何?在早期阶段能够帮助保持应用的结构小巧且易于维护,这样当应用增长时就容易进化了。

Why? Components often have four files (e.g. *.html, *.css, *.ts, and *.spec.ts) and can clutter a folder quickly.

为何?组件通常有四个文件 (*.html*.css*.ts*.spec.ts),它们很容易把一个目录弄乱。

Here is a compliant folder and file structure

下面是符合规范的目录和文件结构

<project root>
app
core
core.module.ts
exception.service.ts|spec.ts
user-profile.service.ts|spec.ts
heroes
hero
hero.component.ts|html|css|spec.ts
hero-list
hero-list.component.ts|html|css|spec.ts
shared
hero-button.component.ts|html|css|spec.ts
hero.model.ts
hero.service.ts|spec.ts
heroes.component.ts|html|css|spec.ts
heroes.module.ts
heroes-routing.module.ts
shared
shared.module.ts
init-caps.pipe.ts|spec.ts
text-filter.component.ts|spec.ts
text-filter.service.ts|spec.ts
villains
villain
...
villain-list
...
shared
...
villains.component.ts|html|css|spec.ts
villains.module.ts
villains-routing.module.ts
app.component.ts|html|css|spec.ts
app.module.ts
app-routing.module.ts
main.ts
index.html
...

While components in dedicated folder are widely preferred, another option for small apps is to keep components flat (not in a dedicated folder). This adds up to four files to the existing folder, but also reduces the folder nesting. Whatever you choose, be consistent.

把组件放在专用目录中的方式广受欢迎,对于小型应用,还可以保持组件扁平化(而不是放在专用目录中)。 这样会把四个文件放在现有目录中,也会减少目录的嵌套。无论你如何选择,请保持一致。

Back to top回到顶部

Folders-by-Feature Structure

按特性组织的目录结构

Style 04-07

风格 04-07

Do create folders named for the feature area they represent.

坚持根据特性区命名目录。

Why? A developer can locate the code, identify what each file represents at a glance, the structure is as flat as it can be, and there is no repetitive nor redundant names.

为何?开发人员可以快速定位代码,扫一眼就能知道每个文件代表什么,目录尽可能保持扁平,既没有重复也没有多余的名字。

Why? The LIFT guidelines are all covered.

为何? LIFT 原则中包含了所有这些。

Why? Helps reduce the app from becoming cluttered through organizing the content and keeping them aligned with the LIFT guidelines.

为何?遵循 LIFT 原则精心组织内容,避免应用变得杂乱无章。

Why? When there are a lot of files (e.g. 10+), locating them is easier with a consistent folder structure and more difficult in a flat structure.

为何?当有很多文件时(例如 10 个以上),在专用目录型结构中定位它们会比在扁平结构中更容易。

Do create an Angular module for each feature area.

坚持为每个特性区创建一个 Angular 模块。

Why? Angular modules make it easy to lazy load routable features.

为何? Angular 模块使延迟加载可路由的特性变得更容易。

Why? Angular modules make it easier to isolate, test, and re-use features.

为何?Angular 模块隔离、测试和复用特性更容易。

Refer here to this Folder and File Structure example点这里查看目录和文件结构的范例
Back to top回到顶部

App Root Module

应用的根模块

Style 04-08

风格 04-08

Do create an Angular module in the app's root folder (e.g., in /app).

坚持在应用的根目录创建一个 Angular 模块(例如/app)。

Why? Every app requires at least one root Angular module.

为何?每个应用都至少需要一个根 Angular 模块。

Consider naming the root module app.module.ts.

考虑把根模块命名为app.module.ts

Why? Makes it easier to locate and identify the root module.

为何?能让定位和识别根模块变得更容易。

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 {}
Back to top回到顶部

Feature Modules

特性模块

Style 04-09

风格 04-09

Do create an Angular module for all distinct features in an application (e.g. Heroes feature).

坚持为应用中每个明显的特性创建一个 Angular 模块。

Do place the feature module in the same named folder as the feature area (.e.g app/heroes).

坚持把特性模块放在与特性区同名的目录中(例如app/heroes)。

Do name the feature module file reflecting the name of the feature area and folder (e.g. app/heroes/heroes.module.ts)

坚持特性模块的文件名应该能反映出特性区的名字和目录(例如app/heroes/heroes.module.ts)。

Do name the feature module symbol reflecting the name of the feature area, folder, and file (e.g. app/heroes/heroes.module.ts defines HeroesModule)

坚持特性模块的符号名应该能反映出特性区、目录和文件名(例如在app/heroes/heroes.module.ts中定义HeroesModule)。

Why? A feature module can expose or hide its implementation from other modules.

为何?特性模块可以对其它模块暴露或隐藏自己的实现。

Why? A feature module identifies distinct sets of related components that comprise the feature area.

为何?特性模块标记出组成该特性分区的相关组件集合。

Why? A feature module can easily be routed to both eagerly and lazily.

为何?方便路由到特性模块 —— 无论是用主动加载还是惰性加载的方式。

Why? A feature module defines clear boundaries between specific functionality and other application features.

为何?特性模块在特定的功能和其它应用特性之间定义了清晰的边界。

Why? A feature module helps clarify and make it easier to assign development responsibilities to different teams.

为何?特性模块帮助澄清开发职责,以便于把这些职责指派给不同的项目组。

Why? A feature module can easily be isolated for testing.

为何?特性模块易于隔离,以便测试。

Back to top回到顶部

Shared Feature Module

共享特性模块

Style 04-10

风格 04-10

Do create a feature module named SharedModule in a shared folder (e.g. app/shared/shared.module.ts defines SharedModule).

坚持shared目录中创建名叫SharedModule的特性模块(例如在app/shared/shared.module.ts中定义SharedModule)。

Do put common components, directives and pipes that will be used throughout the application by other feature modules in the SharedModule, where those assets are expected to share a new instance of themselves (not singletons).

坚持把可能被应用其它特性模块使用的公共组件、指令和管道放在SharedModule中,这些资产倾向于共享自己的新实例(而不是单例)。

Do import all modules required by the assets in the SharedModule (e.g. CommonModule and FormsModule).

坚持SharedModule中导入所有模块都需要的资产(例如CommonModuleFormsModule)。

Why? SharedModule will contain components, directives and pipes that may need features from another common module (e.g. ngFor in CommonModule).

为何? SharedModule中包含的组件、指令和管道可能需要来自其它公共模块的特性(例如来自CommonModule中的ngFor指令)。

Do declare all components, directives, and pipes in the SharedModule.

坚持SharedModule中声明所有组件、指令和管道。

Do export all symbols from the SharedModule that other feature modules need to use.

坚持SharedModule中导出其它特性模块所需的全部符号。

Why? SharedModule exists to make commonly used components, directives and pipes available for use in the templates of components in many other modules.

为何? SharedModule的存在,能让常用的组件、指令和管道在很多其它模块的组件模板中都自动可用。

Avoid specifying app-wide singleton providers in a SharedModule. Intentional singletons are OK. Take care.

避免SharedModule中指定应用级的单例服务提供商。但如果是故意设计的单例也可以,不过还是要小心。

Why? A lazy loaded feature module that imports that shared module will make its own copy of the service and likely have undesireable results.

为何?惰性加载的特性模块如果导入了这个共享模块,会创建一份自己的服务副本,这可能会导致意料之外的后果。

Why? You don't want each module to have its own separate instance of singleton services. Yet there is a real danger of that happening if the SharedModule provides a service.

为何?对于单例服务,你不希望每个模块都有自己的实例。 而如果SharedModule提供了一个服务,那就有可能发生这种情况。

src
app
shared
shared.module.ts
init-caps.pipe.ts|spec.ts
text-filter.component.ts|spec.ts
text-filter.service.ts|spec.ts
app.component.ts|html|css|spec.ts
app.module.ts
app-routing.module.ts
main.ts
index.html
...
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { FilterTextComponent } from './filter-text/filter-text.component'; import { FilterTextService } from './filter-text/filter-text.service'; import { InitCapsPipe } from './init-caps.pipe'; @NgModule({ imports: [CommonModule, FormsModule], declarations: [ FilterTextComponent, InitCapsPipe ], providers: [FilterTextService], exports: [ CommonModule, FormsModule, FilterTextComponent, InitCapsPipe ] }) export class SharedModule { } import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'initCaps' }) export class InitCapsPipe implements PipeTransform { transform = (value: string) => value; } import { Component, EventEmitter, Output } from '@angular/core'; @Component({ moduleId: module.id, selector: 'toh-filter-text', template: '<input type="text" id="filterText" [(ngModel)]="filter" (keyup)="filterChanged($event)" />' }) export class FilterTextComponent { @Output() changed: EventEmitter<string>; filter: string; constructor() { this.changed = new EventEmitter<string>(); } clear() { this.filter = ''; } filterChanged(event: any) { event.preventDefault(); console.log(`Filter Changed: ${this.filter}`); this.changed.emit(this.filter); } } import { Injectable } from '@angular/core'; @Injectable() export class FilterTextService { constructor() { console.log('Created an instance of FilterTextService'); } filter(data: string, props: Array<string>, originalList: Array<any>) { let filteredList: any[]; if (data && props && originalList) { data = data.toLowerCase(); let filtered = originalList.filter(item => { let match = false; for (let prop of props) { if (item[prop].toString().toLowerCase().indexOf(data) > -1) { match = true; break; } }; return match; }); filteredList = filtered; } else { filteredList = originalList; } return filteredList; } } import { Component, OnInit } from '@angular/core'; import { FilterTextService } from '../shared/filter-text/filter-text.service'; @Component({ moduleId: module.id, selector: 'toh-heroes', templateUrl: 'heroes.component.html' }) export class HeroesComponent implements OnInit { filteredHeroes: any[] = []; constructor(private filterService: FilterTextService) { } heroes = [ { id: 1, name: 'Windstorm' }, { id: 2, name: 'Bombasto' }, { id: 3, name: 'Magneta' }, { id: 4, name: 'Tornado' } ]; filterChanged(searchText: string) { this.filteredHeroes = this.filterService.filter(searchText, ['id', 'name'], this.heroes); } ngOnInit() { this.filteredHeroes = this.heroes; } } <div>This is heroes component</div> <ul> <li *ngFor="let hero of filteredHeroes"> {{hero.name}} </li> </ul> <toh-filter-text (changed)="filterChanged($event)"></toh-filter-text> Back to top回到顶部

Core Feature Module

核心特性模块

Style 04-11

风格04-11

Do collect single-use classes and hiding their gory details inside CoreModule. A simplified root AppModule imports CoreModule in its capacity as orchestrator of the application as a whole.

坚持把那些“只用一次”的类收集到CoreModule中,并对外隐藏它们的实现细节。简化的AppModule会导入CoreModule,并且把它作为整个应用的总指挥。

Do create a feature module named CoreModule in a core folder (e.g. app/core/core.module.ts defines CoreModule).

坚持core目录下创建一个名叫CoreModule的特性模块(例如在app/core/core.module.ts中定义CoreModule)。

Do put a singleton service whose instance wil be shared throughout the application in the CoreModule (e.g. ExceptionService and LoggerService).

坚持把一个要共享给整个应用的单例服务放进CoreModule中(例如ExceptionServiceLoggerService)。

Do import all modules required by the assets in the CoreModule (e.g. CommonModule and FormsModule).

坚持导入CoreModule中的资产所需要的全部模块(例如CommonModuleFormsModule)。

Why? CoreModule provides one or more singleton services. Angular registers the providers with the app root injector, making a singleton instance of each service available to any component that needs them, whether that component is eagerly or lazily loaded.

为何? CoreModule提供了一个或多个单例服务。Angular使用应用的根注入器注册这些服务提供商,让每个服务的这个单例对象对所有需要它们的组件都是可用的,而不用管该组件是通过主动加载还是惰性加载的方式加载的。

Why? CoreModule will contain singleton services. When a lazy loaded module imports these, it will get a new instance and not the intended app-wide singleton.

为何?CoreModule将包含一些单例服务。而如果惰性加载模块导入这些服务,它就会得到一个新实例,而不是所期望的全应用级单例。

Do gather application-wide, single use components in the CoreModule. Import it once (in the AppModule) when the app starts and never import it anywhere else. (e.g. NavComponent and SpinnerComponent).

坚持把应用级、只用一次的组件收集到CoreModule中。 只在应用启动时从AppModule中导入它一次,以后再也不要导入它(例如NavComponentSpinnerComponent)。

Why? Real world apps can have several single-use components (e.g., spinners, message toasts, and modal dialogs) that appear only in the AppComponent template. They are not imported elsewhere so they're not shared in that sense. Yet they're too big and messy to leave loose in the root folder.

为何?真实世界中的应用会有很多只用一次的组件(例如加载动画、消息浮层、模态框等),它们只会在AppComponent的模板中出现。 不会在其它地方导入它们,所以没有共享的价值。 然而它们又太大了,放在根目录中就会显得乱七八糟的。

Avoid importing the CoreModule anywhere except in the AppModule.

避免AppModule之外的任何地方导入CoreModule

Why? A lazily loaded feature module that directly imports the CoreModule will make its own copy of services and likely have undesireable results.

为何?如果惰性加载的特性模块直接导入CoreModule,就会创建它自己的服务副本,并导致意料之外的后果。

Why? An eagerly loaded feature module already has access to the AppModule's injector, and thus the CoreModule's services.

为何?主动加载的特性模块已经准备好了访问AppModule的注入器,因此也能取得CoreModule中的服务。

Do export all symbols that from the CoreModule that the AppModule will import and make available for other feature modules to use.

坚持CoreModule中导出AppModule需导入的所有符号,使它们在所有特性模块中可用。

Why? CoreModule exists to make commonly used singleton services available for use in the many other modules.

为何?CoreModule的存在就让常用的单例服务在所有其它模块中可用。

Why? You want the entire app to use the one, singleton instance. You don't want each module to have its own separate instance of singleton services. Yet there is a real danger of that happening accidentally if the CoreModule provides a service.

为何?你希望整个应用都使用这个单例服务。 你不希望每个模块都有这个单例服务的单独的实例。 然而,如果CoreModule中提供了一个服务,就可能偶尔导致这种后果。

src
app
core
core.module.ts
logger.service.ts|spec.ts
nav
nav.component.ts|html|css|spec.ts
spinner
spinner.component.ts|html|css|spec.ts
spinner.service.ts|spec.ts
app.component.ts|html|css|spec.ts
app.module.ts
app-routing.module.ts
main.ts
index.html
...
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; import { CoreModule } from './core/core.module'; @NgModule({ imports: [ BrowserModule, CoreModule, ], declarations: [ AppComponent, HeroesComponent ], exports: [ AppComponent ], entryComponents: [ AppComponent ] }) export class AppModule {} import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoggerService } from './logger.service'; import { NavComponent } from './nav/nav.component'; import { SpinnerComponent } from './spinner/spinner.component'; import { SpinnerService } from './spinner/spinner.service'; @NgModule({ imports: [ CommonModule // we use ngFor ], exports: [NavComponent, SpinnerComponent], declarations: [NavComponent, SpinnerComponent], providers: [LoggerService, SpinnerService] }) export class CoreModule { } import { Injectable } from '@angular/core'; @Injectable() export class LoggerService { log(msg: string) { console.log(msg); } error(msg: string) { console.error(msg); } } import { Component, OnInit } from '@angular/core'; @Component({ moduleId: module.id, selector: 'toh-nav', templateUrl: 'nav.component.html', styleUrls: ['nav.component.css'], }) export class NavComponent implements OnInit { menuItems = [ 'Heroes', 'Villains', 'Other' ]; ngOnInit() { } constructor() { } } <header> <div> <h4>Tour of Heroes</h4> </div> <nav> <ul> <li *ngFor="let item of menuItems"> {{item}} </li> </ul> </nav> <br/> </header> import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LoggerService } from '../logger.service'; import { SpinnerState, SpinnerService } from './spinner.service'; @Component({ moduleId: module.id, selector: 'toh-spinner', templateUrl: 'spinner.component.html', styleUrls: ['spinner.component.css'] }) export class SpinnerComponent implements OnDestroy, OnInit { visible = false; private spinnerStateChanged: Subscription; constructor( private loggerService: LoggerService, private spinnerService: SpinnerService ) { } ngOnInit() { console.log(this.visible); this.spinnerStateChanged = this.spinnerService.spinnerState .subscribe((state: SpinnerState) => { this.visible = state.show; this.loggerService.log(`visible=${this.visible}`); }); } ngOnDestroy() { this.spinnerStateChanged.unsubscribe(); } } <div class="spinner" [class.spinner-hidden]="!visible"> </div> import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; export interface SpinnerState { show: boolean; } @Injectable() export class SpinnerService { private spinnerSubject = new Subject<SpinnerState>(); spinnerState = this.spinnerSubject.asObservable(); constructor() { } show() { this.spinnerSubject.next(<SpinnerState>{ show: true }); } hide() { this.spinnerSubject.next(<SpinnerState>{ show: false }); } }

AppModule is a little smaller because many app/root classes have moved to other modules. AppModule is stable because you will add future components and providers to other modules, not this one. AppModule delegates to imported modules rather than doing work. AppModule is focused on its main task, orchestrating the app as a whole.

AppModule变得更小了,因为很多应用根部的类都被移到了其它模块中。 AppModule变得稳定了,因为你将会往其它模块中添加特性组件和服务提供商,而不是这个AppModuleAppModule把工作委托给了导入的模块,而不是亲力亲为。 AppModule聚焦在它自己的主要任务上:作为整个应用的总指挥。

Back to top回到顶部

Prevent Reimport of Core Module

防止多次导入CoreModule

Style 04-12

风格 04-12

Only the root AppModule should import the CoreModule.

应该只有AppModule才能导入CoreModule

Do guard against reimporting of CoreModule and fail fast by adding guard logic.

坚持防范多次导入CoreModule,并通过添加守卫逻辑来尽快失败。

Why? Guards against reimporting of the CoreModule.

为何?守卫可以阻止对CoreModule的多次导入。

Why? Guards against creating multiple instances of assets intended to be singletons.

为何?守卫会禁止创建单例服务的多个实例。

export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) { if (parentModule) { throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`); } } 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'); } } Back to top回到顶部

Lazy Loaded Folders

惰性加载的目录

Style 04-13

样式 04-13

A distinct application feature or workflow may be lazy loaded or loaded on demand rather than when the application starts.

某些边界清晰的应用特性或工作流可以做成惰性加载按需加载的,而不用总是随着应用启动。

Do put the contents of lazy loaded features in a lazy loaded folder. A typical lazy loaded folder contains a routing component, its child components, and their related assets and modules.

坚持把惰性加载特性下的内容放进惰性加载目录中。 典型的惰性加载目录包含路由组件及其子组件以及与它们有关的那些资产和模块。

Why? The folder makes it easy to identify and isolate the feature content.

为何?这种目录让标识和隔离这些特性内容变得更轻松。

Back to top回到顶部

Never Directly Import Lazy Loaded Folders

永远不要直接导入惰性加载的目录

Style 04-14

样式 04-14

Avoid allowing modules in sibling and parent folders to directly import a module in a lazy loaded feature.

避免让兄弟模块和父模块直接导入惰性加载特性中的模块。

Why? Directly importing and using a module will load it immediately when the intention is to load it on demand.

为何?直接导入并使用此模块会立即加载它,而原本的设计意图是按需加载它。

Back to top回到顶部

Components

组件

Component Selector Naming

组件选择器命名

Style 05-02

风格05-02

Do use dashed-case or kebab-case for naming the element selectors of components.

坚持使用中线 (dashed) 命名法烤串 (kebab) 命名法来命名组件中的元素选择器。

Why? Keeps the element names consistent with the specification for Custom Elements.

为何?保持元素命名与自定义元素命名规范一致。

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: 'tohHeroButton', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {}
@Component({ selector: 'toh-hero-button', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {} <toh-hero-button></toh-hero-button> Back to top回到顶部

Components as Elements

把组件当做元素

Style 05-03

风格 05-03

Do define components as elements via the selector.

坚持通过选择器把组件定义为元素。

Why? components have templates containing HTML and optional Angular template syntax. They are most associated with putting content on a page, and thus are more closely aligned with elements.

为何?组件有很多包含 HTML 以及可选 Angular 模板语法的模板。它们多数都与把内容放进页面有关,因而组件更接近于元素。

Why? A component represents a visual element on the page. Defining the selector as an HTML element tag is consistent with native HTML elements and WebComponents.

为何?组件代表页面上的一个可视元素。 把选择器定义成 HTML 元素标签可以与原生 HTML 元素和 WebComponent 保持一致。

Why? It is easier to recognize that a symbol is a component vs a directive by looking at the template's html.

为何?查看组件模板的 HTML 时,更容易识别一个符号是组件还是指令。

app/heroes/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: '[tohHeroButton]', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {}

app/app.component.html

<!-- avoid --> <div tohHeroButton></div>
@Component({ selector: 'toh-hero-button', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {} <toh-hero-button></toh-hero-button> Back to top回到顶部

Extract Template and Styles to Their Own Files

把模板和样式提取到它们自己的文件

Style 05-04

风格 05-04

Do extract templates and styles into a separate file, when more than 3 lines.

坚持当超过 3 行时,把模板和样式提取到一个单独的文件。

Do name the template file [component-name].component.html, where [component-name] is the component name.

坚持把模板文件命名为[component-name].component.html,其中,[component-name] 是组件名。

Do name the style file [component-name].component.css, where [component-name] is the component name.

坚持把样式文件命名为[component-name].component.css,其中,[component-name] 是组件名。

Why? Syntax hints for inline templates in (.js and .ts) code files are not supported by some editors.

为何?在 (.js 和 .ts) 代码里面内联模板时,某些编辑器不支持语法提示。

Why? A component file's logic is easier to read when not mixed with inline template and styles.

为何?当没有与内联模板和样式混合时,组件文件中的逻辑更易于阅读。

app/heroes/heroes.component.ts

/* avoid */ @Component({ selector: 'toh-heroes', template: ` <div> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{selectedHero.name | uppercase}} is my hero</h2> </div> </div> `, styleUrls: [` .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; } `] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; ngOnInit() {} }
@Component({ selector: 'toh-heroes', templateUrl: 'heroes.component.html', styleUrls: ['heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; ngOnInit() { } } <div> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{selectedHero.name | uppercase}} is my hero</h2> </div> </div> .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; } Back to top回到顶部

Decorate Input and Output Properties Inline

内联输入和输出属性装饰器

Style 05-12

风格 05-12

Do use @Input and @Output instead of the inputs and outputs properties of the @Directive and@Component` decorators:

坚持 使用@Input@Output,而非@Directive@Component装饰器的inputsoutputs属性:

Do place the @Input() or @Output() on the same line as the property they decorate.

坚持@Input()或者@Output()放到所装饰的属性的同一行。

Why? It is easier and more readable to identify which properties in a class are inputs or outputs.

为何?易于在类里面识别哪些属性是输入属性或输出属性。

Why? If you ever need to rename the property or event name associated with @Input or @Output, you can modify it a single place.

为何? 如果需要重命名与@Input或者@Output关联的属性或事件名,你可以在一个位置修改。

Why? The metadata declaration attached to the directive is shorter and thus more readable.

为何?依附到指令的元数据声明会比较简短,更易于阅读。

Why? Placing the decorator on the same line makes for shorter code and still easily identifies the property as an input or output.

为何?把装饰器放到同一行可以精简代码,同时更易于识别输入或输出属性。

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @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; }
Back to top回到顶部

Avoid Renaming Inputs and Outputs

避免重命名输入和输出

Style 05-13

风格 05-13

Avoid renaming inputs and outputs, when possible.

避免重命名输入和输出。

Why? May lead to confusion when the output or the input properties of a given directive are named a given way but exported differently as a public API.

为何?当指令的输入或输出属性的名字与导出的公共 API 名字不一样时,可能导致混乱。

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output('changeEvent') change = new EventEmitter<any>(); @Input('labelAttribute') label: string; }

app/app.component.html

<!-- avoid --> <toh-hero-button labelAttribute="OK" (changeEvent)="doSomething()"> </toh-hero-button>
@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output() change = new EventEmitter<any>(); @Input() label: string; } <toh-hero-button label="OK" (change)="doSomething()"> </toh-hero-button> Back to top回到顶部

Member Sequence

成员顺序

Style 05-14

风格 05-14

Do place properties up top followed by methods.

坚持把属性成员放在前面,方法成员放在后面。

Do place private members after public members, alphabetized.

坚持先放公共成员,再放私有成员,并按照字母顺序排列。

Why? Placing members in a consistent sequence makes it easy to read and helps instantly identify which members of the component serve which purpose.

为何?把类的成员按照统一的顺序排列,易于阅读,能立即识别出组件的哪个成员服务于何种目的。

app/shared/toast/toast.component.ts

/* avoid */ 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); } }
Back to top回到顶部

Put Logic in Services

把逻辑放到服务里

Style 05-15

风格 05-15

Do limit logic in a component to only that required for the view. All other logic should be delegated to services.

坚持在组件中只包含与视图相关的逻辑。所有其它逻辑都应该放到服务中。

Do move reusable logic to services and keep components simple and focused on their intended purpose.

坚持把可重用的逻辑放到服务中,保持组件简单,聚焦于它们预期目的。

Why? Logic may be reused by multiple components when placed within a service and exposed via a function.

为何?当逻辑被放置到服务里,并以函数的形式暴露时,可以被多个组件重复使用。

Why? Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked.

为何?在单元测试时,服务里的逻辑更容易被隔离。当组件中调用逻辑时,也很容易被模拟。

Why? Removes dependencies and hides implementation details from the component.

为何?从组件移除依赖并隐藏实施细节。

Why? Keeps the component slim, trim, and focused.

为何?保持组件苗条、精简和聚焦。

app/heroes/hero-list/hero-list.component.ts

/* avoid */ import { OnInit } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Hero } from '../shared/hero.model'; const heroesUrl = 'http://angular.io'; export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private http: Http) {} getHeroes() { this.heroes = []; this.http.get(heroesUrl) .map((response: Response) => <Hero[]>response.json().data) .catch(this.catchBadResponse) .finally(() => this.hideSpinner()) .subscribe((heroes: Hero[]) => this.heroes = heroes); } ngOnInit() { this.getHeroes(); } private catchBadResponse(err: any, source: Observable<any>) { // log and handle the exception return new Observable(); } private hideSpinner() { // hide the spinner } }

app/heroes/hero-list/hero-list.component.ts

import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from '../shared'; @Component({ selector: 'toh-hero-list', template: `...` }) export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private heroService: HeroService) {} getHeroes() { this.heroes = []; this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } ngOnInit() { this.getHeroes(); } }
Back to top回到顶部

Don't Prefix Output Properties

不要给输出属性加前缀

Style 05-16

风格 05-16

Do name events without the prefix on.

坚持命名事件时,不要带前缀on

Do name event handler methods with the prefix on followed by the event name.

坚持把事件处理器方法命名为on前缀之后紧跟着事件名。

Why? This is consistent with built-in events such as button clicks.

为何?与内置事件命名一致,例如按钮点击。

Why? Angular allows for an alternative syntax on-*. If the event itself was prefixed with on this would result in an on-onEvent binding expression.

为何?Angular 允许另一种备选语法 on-*。如果事件的名字本身带有前缀on,那么绑定的表达式可能是on-onEvent

app/heroes/hero.component.ts

/* avoid */ @Component({ selector: 'toh-hero', template: `...` }) export class HeroComponent { @Output() onSavedTheDay = new EventEmitter<boolean>(); }

app/app.component.html

<!-- avoid --> <toh-hero (onSavedTheDay)="onSavedTheDay($event)"></toh-hero>
export class HeroComponent { @Output() savedTheDay = new EventEmitter<boolean>(); } <toh-hero (savedTheDay)="onSavedTheDay($event)"></toh-hero> Back to top回到顶部

Put Presentation Logic in the Component Class

把表现层逻辑放到组件类里

Style 05-17

风格 05-17

Do put presentation logic in the component class, and not in the template.

坚持把表现层逻辑放进组件类中,而不要放在模板里。

Why? Logic will be contained in one place (the component class) instead of being spread in two places.

为何?逻辑应该只出现在一个地方(组件类里)而不应分散在两个地方。

Why? Keeping the component's presentation logic in the class instead of the template improves testability, maintainability, and reusability.

为何?将组件的表现层逻辑放到组件类而非模板里,可以增强测试性、维护性和重复使用性。

app/heroes/hero-list/hero-list.component.ts

/* avoid */ @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; } }
Back to top回到顶部

Directives

指令

Back to top

Use Directives to Enhance an Existing Element

使用指令来加强已有元素

Style 06-01

风格 06-01

Do use attribute directives when you have presentation logic without a template.

坚持当你需要有表现层逻辑,但没有模板时,使用属性型指令。

Why? Attributes directives don't have an associated template.

为何?属性型指令没有模板。

Why? An element may have more than one attribute directive applied.

为何?一个元素可以使用多个属性型指令。

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>
Back to top回到顶部

Use HostListener and HostBinding Class Decorators

使用 HostListener 和 HostBinding 类装饰器

Style 06-03

风格 06-03

Consider preferring the @HostListener and @HostBinding to the host property of the @Directive and @Component decorators.

考虑优先使用@HostListener@HostBinding,而不是@Directive@Component装饰器的host属性。

Do be consistent in your choice.

坚持让你的选择保持一致。

Why? The property associated with @HostBinding or the method associated with @HostListener can be modified only in a single place - in the directive's class. If you use the host metadata property, you must modify both the property declaration inside the controller, and the metadata associated with the directive.

为何?对于关联到@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 } }

Compare with the less preferred host metadata alternative.

与不推荐的方式(host元数据)比较一下。

Why? The host metadata is only one term to remember and doesn't require extra ES imports.

为何?host元数据只是一个便于记忆的名字而已,并不需要额外的 ES 导入。

app/shared/validator2.directive.ts

import { Directive } from '@angular/core'; @Directive({ selector: '[tohValidator2]', host: { 'attr.role': 'button', '(mouseenter)': 'onMouseEnter()' } }) export class Validator2Directive { role = 'button'; onMouseEnter() { // do work } }
Back to top回到顶部

Services

服务

Services are Singletons within an Injector

注入器中,服务总是单例的

Style 07-01

风格 07-01

Do use services as singletons within the same injector. Use them for sharing data and functionality.

坚持在同一个注入器内,把服务当做单例使用。用它们来共享数据和功能。

Why? Services are ideal for sharing methods across a feature area or an app.

为何?服务是在特性范围或应用内共享方法的理想载体。

Why? Services are ideal for sharing stateful in-memory data.

为何?服务是共享状态性内存数据的理想载体。

app/heroes/shared/hero.service.ts

export class HeroService { constructor(private http: Http) { } getHeroes() { return this.http.get('api/heroes') .map((response: Response) => <Hero[]>response.json().data); } }
Back to top回到顶部

Single Responsibility

单一职责

Style 07-02

风格 07-02

Do create services with a single responsibility that is encapsulated by its context.

坚持创建单一职责的服务,用职责封装在它的上下文中。

Do create a new service once the service begins to exceed that singular purpose.

坚持当服务成长到超出单一用途时,创建一个新服务。

Why? When a service has multiple responsibilities, it becomes difficult to test.

为何?当服务有多个职责时,它很难被测试。

Why? When a service has multiple responsibilities, every component or service that injects it now carries the weight of them all.

为何?当某个服务有多个职责时,每个注入它的组件或服务都会承担这些职责的全部开销。

Back to top回到顶部

Providing a Service

提供一个服务

Style 07-03

风格 07-03

Do provide services to the Angular injector at the top-most component where they will be shared.

坚持将服务提供到共享范围内的顶级组件的 Angular 注入器。

Why? The Angular injector is hierarchical.

为何? Angular 注入器是层次化的。

Why? When providing the service to a top level component, that instance is shared and available to all child components of that top level component.

为何?在顶层组件提供服务时,该服务实例在所有子组件中可见并共享。

Why? This is ideal when a service is sharing methods or state.

为何?服务是共享方法或状态的理想载体。

Why? This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance.

为何?当不同的两个组件需要一个服务的不同的实例时,上面的方法这就不理想了。在这种情况下,对于需要崭新和单独服务实例的组件,最好在组件级提供服务。

import { Component } from '@angular/core'; import { HeroService } from './heroes'; @Component({ selector: 'toh-app', template: ` <toh-heroes></toh-heroes> `, providers: [HeroService] }) export class AppComponent {} import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from '../shared'; @Component({ selector: 'toh-heroes', template: ` <pre>{{heroes | json}}</pre> ` }) export class HeroListComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) { } ngOnInit() { this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes); } } Back to top回到顶部

Use the @Injectable() Class Decorator

使用 @Injectable() 类装饰器

Style 07-04

风格 07-04

Do use the @Injectable class decorator instead of the @Inject parameter decorator when using types as tokens for the dependencies of a service.

坚持当使用类型作为令牌来注入服务的依赖时,使用@Injectable类装饰器,而非@Inject参数装饰器。

Why? The Angular DI mechanism resolves all dependencies of services based on their types declared with the services' constructors.

为何? Angular 的 DI 机制会根据服务的构造函数参数的声明类型来解析服务的所有依赖。

Why? When a service accepts only dependencies associated with type tokens, the @Injectable() syntax is much less verbose compared to using @Inject() on each individual constructor parameter.

为何?当服务只接受类型令牌相关的依赖时,比起在每个构造函数参数上使用@Inject()@Injectable()的语法简洁多了。

app/heroes/shared/hero-arena.service.ts

/* avoid */ 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) {} }
Back to top回到顶部

Data Services

数据服务

Separate Data Calls

分离数据调用

Style 08-01

风格 08-01

Do refactor logic for making data operations and interacting with data to a service.

坚持把数据操作和互动重构到服务里。

Do make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.

坚持让数据服务来负责 XHR 调用、本地储存、内存储存或者其它数据操作。

Why? The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view.

为何?组件的职责是为视图展示或收集信息。它不应该关心如何获取数据,它只需要知道向谁请求数据。把如何获取数据的逻辑移动到数据服务里,简化了组件,让其聚焦于视图。

Why? This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.

为何?在测试使用数据服务的组件时,可以让数据调用更容易被测试(模拟或者真实)。

Why? Data service implementation may have very specific code to handle the data repository. This may include headers, how to talk to the data, or other services such as Http. Separating the logic into a data service encapsulates this logic in a single place hiding the implementation from the outside consumers (perhaps a component), also making it easier to change the implementation.

为何?数据服务的实现可能有非常具体的代码来处理数据仓库,包括数据头 (headers)、如何与数据交谈或者其它服务 (例如Http)。把逻辑分离到数据服务可以将该逻辑封装在一个地方,对外部使用者(例如组件)隐藏具体的实施细节。

Back to top回到顶部

Lifecycle Hooks

生命周期钩子

Use Lifecycle Hooks to tap into important events exposed by Angular.

使用生命周期钩子来介入到 Angular 暴露的重要事件里。

Back to top回到顶部

Implement Lifecycle Hooks Interfaces

实现生命周期钩子接口

Style 09-01

风格 09-01

Do implement the lifecycle hook interfaces.

坚持实现生命周期钩子接口。

Why? Strongly-typed method signatures. The compiler and editor can call out misspellings.

为何?如果使用强类型的方法签名,编译器和编辑器可以帮你揪出拼写错误。

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @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'); } }
Back to top回到顶部

Appendix

附录

Useful tools and tips for Angular.

有用的 Angular 工具和小提示

Back to top回到顶部

Codelyzer

Codelyzer

Style A-01

风格 A-01

Do use codelyzer to follow this guide.

坚持使用 codelyzer 来实施本指南。

Consider adjusting the rules in codelyzer to suit your needs.

考虑调整 codelyzer 的规则来满足你的需求。

Back to top回到顶部

File Templates and Snippets

文档模板和代码片段

Style A-02

风格 A-02

Do use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs.

坚持使用文件模板或代码片段来帮助实现一致的风格和模式。下面是为一些网络开发编辑器和 IDE 准备的模板和/或代码片段:

Consider using snippets for Visual Studio Code that follow these styles and guidelines.

考虑使用 Visual Studio Code代码片段 来实施本风格指南。

Use Extension

Consider using snippets for Atom that follow these styles and guidelines.

考虑使用 Atom代码片断来实施本风格指南。

Consider using snippets for Sublime Text that follow these styles and guidelines.

考虑使用 Sublime Text代码片断 来实施本风格指南。

Consider using snippets for Vim that follow these styles and guidelines.

考虑使用 Vim代码片断来实施本风格指南。

Back to top回到顶部