' }) 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); } }
Consider collecting numerous, auxiliary, single-use classes inside a core module to simplify the apparent structure of a feature module.
考虑把那些数量庞大、辅助性的、只用一次的类收集到核心模块中,让特性模块的结构更清晰简明。
Consider calling the application-wide core module, CoreModule
. Importing CoreModule
into the root AppModule
reduces its complexity and emphasizes its role 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 will be shared throughout the application in the CoreModule
(e.g. ExceptionService
and LoggerService
).
坚持把要共享给整个应用的单例服务放进 CoreModule
中(例如 ExceptionService
和 LoggerService
)。
Do import all modules required by the assets in the CoreModule
(e.g. CommonModule
and FormsModule
).
坚持导入 CoreModule
中的资产所需要的全部模块(例如 CommonModule
和 FormsModule
)。
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
中导入它一次,以后再也不要导入它(例如 NavComponent
和 SpinnerComponent
)。
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 undesirable 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 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
...
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
变得稳定了,因为你将会往其它模块中添加特性组件和服务提供商,而不是这个 AppModule
。 AppModule
把工作委托给了导入的模块,而不是亲力亲为。 AppModule
聚焦在它自己的主要任务上:作为整个应用的总指挥。
CoreModule
linkOnly 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.
为何?守卫会禁止创建单例服务的多个实例。
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.
为何?这种目录让标识和隔离这些特性内容变得更轻松。
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.
为何?直接导入并使用此模块会立即加载它,而原本的设计意图是按需加载它。
Consider giving components an element selector, as opposed to attribute or class selectors.
考虑给组件一个元素选择器,而不是属性或类选择器。
Why? components have templates containing HTML and optional Angular template syntax. They display content. Developers place components on the page as they would native HTML elements and web components.
为何?组件有很多包含 HTML 以及可选 Angular 模板语法的模板。 它们显示内容。开发人员会把组件像原生 HTML 元素和 WebComponents 一样放进页面中。
Why? It is easier to recognize that a symbol is a component by looking at the template's html.
为何?查看组件模板的 HTML 时,更容易识别一个符号是组件还是指令。
There are a few cases where you give a component an attribute, such as when you want to augment a built-in element. For example, Material Design uses this technique with <button mat-button>
. However, you wouldn't use this technique on a custom element.
少数情况下,你要为组件使用属性选择器,比如你要加强某个内置元素时。 比如,Material Design 组件库就会对 <button mat-button>
使用这项技术。不过,你不应该在自定义组件上使用这项技术。
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] 是组件名。
Do specify component-relative URLs, prefixed with ./
.
坚持指定相对于模块的 URL ,给它加上 ./
前缀。
Why? Large, inline templates and styles obscure the component's purpose and implementation, reducing readability and maintainability.
为何?巨大的、内联的模板和样式表会遮盖组件的意图和实现方式,削弱可读性和可维护性。
Why? In most editors, syntax hints and code snippets aren't available when developing inline templates and styles. The Angular TypeScript Language Service (forthcoming) promises to overcome this deficiency for HTML templates in those editors that support it; it won't help with CSS styles.
为何?在多数编辑器中,编写内联的模板和样式表时都无法使用语法提示和代码片段功能。 Angular 的 TypeScript 语言服务(即将到来)可以帮助那些编辑器在编写 HTML 模板时克服这一缺陷,但对 CSS 样式没有帮助。
Why? A component relative URL requires no change when you move the component files, as long as the files stay together.
为何?当你移动组件文件时,相对于组件的 URL 不需要修改,因为这些文件始终会在一起。
Why? The ./
prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix.
为何?./
前缀是相对 URL 的标准语法,不必依赖 Angular 的特殊处理,如果没有前缀则不行。
Do use the @Input()
and @Output()
class decorators instead of the inputs
and outputs
properties of the @Directive
and @Component
metadata:
坚持 使用 @Input()
和 @Output()
,而非 @Directive
和 @Component
装饰器的 inputs
和 outputs
属性:
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 in a single place.
Why? The metadata declaration attached to the directive is shorter and thus more readable.
为何?依附到指令的元数据声明会比较简短,更易于阅读。
Why? Placing the decorator on the same line usually makes for shorter code and still easily identifies the property as an input or output. Put it on the line above when doing so is clearly more readable.
为何?把装饰器放到同一行可以精简代码,同时更易于识别输入或输出属性。
Avoid input and output aliases except when it serves an important purpose.
避免除非有重要目的,否则不要为输入和输出指定别名。
Why? Two names for the same property (one private, one public) is inherently confusing.
为何?同一个属性有两个名字(一个对内一个对外)很容易导致混淆。
Why? You should use an alias when the directive name is also an input property, and the directive name doesn't describe the property.
为何?如果指令名也同时用作输入属性,而且指令名无法准确描述这个属性的用途时,应该使用别名。
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.
为何?把类的成员按照统一的顺序排列,易于阅读,能立即识别出组件的哪个成员服务于何种目的。
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.
为何?保持组件苗条、精简和聚焦。
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
。
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.
为何?将组件的表现层逻辑放到组件类而非模板里,可以增强测试性、维护性和重复使用性。
Do use attribute directives when you have presentation logic without a template.
坚持当你需要有表现层逻辑,但没有模板时,使用属性型指令。
Why? Attribute directives don't have an associated template.
为何?属性型指令没有模板。
Why? An element may have more than one attribute directive applied.
为何?一个元素可以使用多个属性型指令。
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/method declaration in the directive's class and the metadata in the decorator associated with the directive.
为何?对于关联到 @HostBinding
的属性或关联到 @HostListener
的方法,要修改时,只需在指令类中的一个地方修改。 如果使用元数据属性 host
,你就得在组件类中修改属性声明的同时修改相关的元数据。
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 导入。
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.
为何?服务是共享状态性内存数据的理想载体。
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.
为何?当某个服务有多个职责时,每个注入它的组件或服务都会承担这些职责的全部开销。
Do provide a service with the app root injector in the @Injectable
decorator of the service.
坚持在服务的 @Injectable
装饰器上指定通过应用的根注入器提供服务。
Why? The Angular injector is hierarchical.
为何? Angular 注入器是层次化的。
Why? When you provide the service to a root injector, that instance of the service is shared and available in every class that needs the service. This is ideal when a service is sharing methods or state.
为何?当你在根注入器上提供该服务时,该服务实例在每个需要该服务的类中是共享的。当服务要共享方法或状态时,这是最理想的选择。
Why? When you register a service in the @Injectable
decorator of the service, optimization tools such as those used by the CLI's production builds can perform tree shaking and remove services that aren't used by your app.
为何?当你在服务的 @Injectable
中注册服务时,CLI 生产环境构建时使用的优化工具可以进行摇树优化,从而移除那些你的应用中从未用过的服务。
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.
为何?当不同的两个组件需要一个服务的不同的实例时,上面的方法这就不理想了。在这种情况下,对于需要崭新和单独服务实例的组件,最好在组件级提供服务。
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 Dependency Injection (DI) mechanism resolves a service's own dependencies based on the declared types of that service's constructor parameters.
为何? 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()
的语法简洁多了。
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? The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers.
为何?数据管理的详情,比如头信息、方法、缓存、错误处理和重试逻辑,不是组件和其它的数据消费者应该关心的事情。
A data service encapsulates these details. It's easier to evolve these details inside the service without affecting its consumers. And it's easier to test the consumers with mock service implementations.
数据服务应该封装这些细节。这样,在服务内部修改细节,就不会影响到它的消费者。并且更容易通过实现一个模拟服务来对消费者进行测试。
Use Lifecycle hooks to tap into important events exposed by Angular.
使用生命周期钩子来介入到 Angular 暴露的重要事件里。
Do implement the lifecycle hook interfaces.
坚持实现生命周期钩子接口。
Why? Lifecycle interfaces prescribe typed method signatures. use those signatures to flag spelling and syntax mistakes.
为何?如果使用强类型的方法签名,编译器和编辑器可以帮你揪出拼写错误。
Useful tools and tips for Angular.
有用的 Angular 工具和小提示
Consider adjusting the rules in codelyzer to suit your needs.
考虑调整 codelyzer 的规则来满足你的需求。
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的代码片段 来实施本风格指南。
Consider using snippets for Atom that follow these styles and guidelines.
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.