fix: 合并了最新版本

This commit is contained in:
Zhicheng Wang 2018-03-24 13:12:42 +08:00
parent ac300b3db1
commit 6c3d57aee9
52 changed files with 1540 additions and 1687 deletions

View File

@ -333,7 +333,7 @@ JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the
### *annotationsAs*
Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular
annotations and decorators are unnaffected. Default is `static fields`.
annotations and decorators are unaffected. Default is `static fields`.
使用这个选项来修改生成 Angular 特有注解的方式以提升摇树优化tree-shaking的效果。它对 Angular 自身之外的注解和装饰器无效。
默认值是 `static fields`
@ -349,16 +349,6 @@ This tells the compiler to print extra information while compiling templates.
它告诉编译器在编译模板时打印额外的信息。
### *enableLegacyTemplate*
The use of `<template>` element was deprecated starting in Angular 4.0 in favor of using
`<ng-template>` to avoid colliding with the DOM's element of the same name. Setting this option to
`true` enables the use of the deprecated `<template>` element . This option
is `false` by default. This option might be required by some third-party Angular libraries.
从 Angular 4.0 开始,`<template>` 元素已经被废弃了,要改用 `<ng-template>` 以避免和同名 DOM 元素的冲突。把该选项设置为 `true` 将会允许使用已废弃的 `<template>` 元素。
该选项默认为 `false`。某些第三方 Angular 库可能会需要该选项。
### *disableExpressionLowering*
The Angular template compiler transforms code that is used, or could be used, in an annotation
@ -444,7 +434,7 @@ export class TypicalComponent {
```
The Anglar compiler extracts the metadata _once_ and generates a _factory_ for `TypicalComponent`.
The Angular compiler extracts the metadata _once_ and generates a _factory_ for `TypicalComponent`.
When it needs to create a `TypicalComponent` instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.
Angular 编译器只提取**一次**元数据,并且为 `TypicalComponent` 生成一个**工厂**。
@ -1706,7 +1696,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
{@a binding-expresion-validation}
## Phase 3: binding expression validation
## 阶段 3验证绑定表达式
In the validation phase, the Angular template compiler uses the TypeScript compiler to validate the
@ -1775,7 +1765,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
比如,如果指定了 `strictTypeChecks`,就会像上面的错误信息一样报告 ```my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined'``` 错误。
### Type narrowing
### 类型窄化
The expression used in an `ngIf` directive is used to narrow type unions in the Angular
@ -1804,7 +1794,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
使用 `*ngIf` 能让 TypeScript 编译器推断出这个绑定表达式中使用的 `person` 永远不会是 `undefined`
#### Custom `ngIf` like directives
#### 类似于的 `ngIf` 的自定义指令
Directives that behave like `*ngIf` can declare that they want the same treatment by including
@ -1826,7 +1816,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
它声明了 `NgIf` 指令的 `ngIf` 属性应该在用到它的模板中看做一个守卫,以表明只有当 `ngIf` 这个输入属性为 `true` 时,才应该生成那个模板。
### Non-null type assertion operator
### 非空类型断言操作符
Use the [non-null type assertion operator](guide/template-syntax#non-null-assertion-operator)
@ -1891,7 +1881,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
```
### Disabling type checking using `$any()`
### 使用 `$any()` 禁用类型检查
Disable checking of a binding expression by surrounding the expression

View File

@ -5,9 +5,7 @@
</div>
<header class="api-header">
<h1><label class="api-status-label experimental">experimental</label><label class="api-type-label class">class</label>Class Name</h1>
</header>
<div class="page-actions">

View File

@ -0,0 +1,212 @@
# Introduction to components
<img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left">
A _component_ controls a patch of screen called a *view*. For example, individual components define and control each of the following views from the [Tutorial](tutorial/index):
* The app root with the navigation links.
带有导航链接的应用根组件。
* The list of heroes.
英雄列表。
* The hero editor.
英雄编辑器。
You define a component's application logic&mdash;what it does to support the view&mdash;inside a class. The class interacts with the view through an API of properties and methods.
你在类中定义组件的应用逻辑,为视图提供支持。
组件通过一些由属性和方法组成的 API 与视图交互。
For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example>
Angular creates, updates, and destroys components as the user moves through the application. Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()`.
<hr/>
## Component metadata
<img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left">
The `@Component` decorator identifies the class immediately below it as a component class, and specifies its metadata. In the example code below, you can see that `HeroListComponent` is just a class, with no special Angular notation or syntax at all. It's not a component until mark it as one with the `@Component` decorator.
The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. In particular, it associates a _template_ with the component, either directly with inline code, or by reference. Together, the component and its template describe a _view_.
In addition to containing or pointing to the template, the `@Component` metadata configures, for example, how the component can be referenced in HTML and what services it requires.
Here's an example of basic metadata for `HeroListComponent`:
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example>
This example shows some of the most useful `@Component` configuration options:
* `selector`: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then
Angular inserts an instance of the `HeroListComponent` view between those tags.
* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.
* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance
in order to get the list of heroes to display.
<hr/>
## Templates and views
<img src="generated/images/guide/architecture/template.png" alt="Template" class="left">
You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component.
Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's _host view_. The component can also define a _view hierarchy_, which contains _embedded views_, hosted by other components.
<figure>
<img src="generated/images/guide/architecture/component-tree.png" alt="Component tree" class="left">
</figure>
A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules.
## Template syntax
A template looks like regular HTML, except that it also contains Angular [template syntax](guide/template-syntax), which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use _data binding_ to coordinate the app and DOM data, _pipes_ to transform data before it is displayed, and _directives_ to apply app logic to what gets displayed.
For example, here is a template for the Tutorial's `HeroListComponent`:
<code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example>
This template uses typical HTML elements like `<h2>` and `<p>`, and also includes Angular template-syntax elements, `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>`. The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data.
* The `*ngFor` directive tells Angular to iterate over a list.
* The `{{hero.name}}`, `(click)`, and `[hero]` bind program data to and from the DOM, responding to user input. See more about [data binding](#data-binding) below.
* The `<app-hero-detail>` tag in the example is an element that represents a new component, `HeroDetailComponent`. The `HeroDetailComponent` (code not shown) is a child component of the `HeroListComponent` that defines the Hero-detail view. Notice how custom components like this mix seamlessly with native HTML in the same layouts.
### Data binding
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced jQuery programmer can attest.
Angular supports *two-way data binding*, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.
The following diagram shows the four forms of data binding markup. Each form has a direction&mdash;to the DOM, from the DOM, or in both directions.
<figure>
<img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left">
</figure>
This example from the `HeroListComponent` template uses three of these forms:
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example>
* The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation)
displays the component's `hero.name` property value within the `<li>` element.
`{{hero.name}}`[*插值表达式*](guide/displaying-data#interpolation)在 `<li>` 标签中显示组件的 `hero.name` 属性的值。
* The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from
the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`.
`[hero]`[*属性绑定*](guide/template-syntax#property-binding)把父组件 `HeroListComponent``selectedHero` 的值传到子组件 `HeroDetailComponent``hero` 属性中。
* The `(click)` [*event binding*](guide/user-input#binding-to-user-input-events) calls the component's `selectHero` method when the user clicks a hero's name.
**Two-way data binding** is an important fourth form that combines property and event binding in a single notation. Here's an example from the `HeroDetailComponent` template that uses two-way data binding with the `ngModel` directive:
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
In two-way binding, a data property value flows to the input box from the component as with property binding.
The user's changes also flow back to the component, resetting the property to the latest value,
as with event binding.
在双向绑定中,数据属性值通过属性绑定从组件流到输入框。用户的修改通过事件绑定流回组件,把属性值设置为最新的值。
Angular processes *all* data bindings once per JavaScript event cycle,
from the root of the application component tree through all child components.
Angular 在每个 JavaScript 事件循环中处理*所有的*数据绑定,它会从组件树的根部开始,递归处理全部子组件。
<figure>
<img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding" class="left">
</figure>
Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components.
<figure>
<img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding" class="left">
</figure>
### Pipes
### 管道
Angular pipes let you declare display-value transformations in your template HTML. A class with the `@Pipe` decorator defines a function that transforms input values to output values for display in a view.
Angular defines various pipes, such as the [date](https://angular.io/api/common/DatePipe) pipe and [currency](https://angular.io/api/common/CurrencyPipe) pipe; for a complete list, see the [Pipes API list](https://angular.io/api?type=pipe). You can also define new pipes.
To specify a value transformation in an HTML template, use the [pipe operator (|)](https://angular.io/guide/template-syntax#pipe):
`{{interpolated_value | pipe_name}}`
You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the `date` pipe:
```
<!-- Default format: output 'Jun 15, 2015'-->
<p>Today is {{today | date}}</p>
<!-- fullDate format: output 'Monday, June 15, 2015'-->
<p>The date is {{today | date:'fullDate'}}</p>
<!-- shortTime format: output '9:43 AM'-->
<p>The time is {{today | date:'shortTime'}}</p>
```
<hr/>
### Directives
<img src="generated/images/guide/architecture/directive.png" alt="Directives" class="left">
Angular templates are *dynamic*. When Angular renders them, it transforms the DOM according to the instructions given by *directives*. A directive is a class with a `@Directive` decorator.
A component is technically a directive - but components are so distinctive and central to Angular applications that Angular defines the `@Component` decorator, which extends the `@Directive` decorator with template-oriented features.
There are two kinds of directives besides components: _structural_ and _attribute_ directives. Just as for components, the metadata for a directive associates the class with a `selector` that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding.
#### Structural directives
Structural directives alter layout by adding, removing, and replacing elements in DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered:
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example>
* [`*ngFor`](guide/displaying-data#ngFor) is an iterative; it tells Angular to stamp out one `<li>` per hero in the `heroes` list.
* [`*ngIf`](guide/displaying-data#ngIf) is a conditional; it includes the `HeroDetail` component only if a selected hero exists.
#### Attribute directives
Attribute directives alter the appearance or behavior of an existing element.
In templates they look like regular HTML attributes, hence the name.
The `ngModel` directive, which implements two-way data binding, is an example of an attribute directive. `ngModel` modifies the behavior of an existing element (typically an `<input>`) by setting its display value property and responding to change events.
`ngModel` 指令就是属性型指令的一个例子,它实现了双向数据绑定。
`ngModel` 修改现有元素(一般是 `<input>`)的行为:设置其显示属性值,并响应 change 事件。
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
Angular has more pre-defined directives that either alter the layout structure
(for example, [ngSwitch](guide/template-syntax#ngSwitch))
or modify aspects of DOM elements and components
(for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)).
You can also write your own directives. Components such as `HeroListComponent` are one kind of custom directive. You can also create custom structural and attribute directives.
<!-- PENDING: link to where to learn more about other kinds! -->

View File

@ -0,0 +1,123 @@
# Introduction to modules
<img src="generated/images/guide/architecture/module.png" alt="Module" class="left">
Angular apps are modular and Angular has its own modularity system called _NgModules_. An NgModule is a container for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. It can contain components, service providers, and other code files whose scope is defined by the containing NgModule. It can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.
Every Angular app has at least one NgModule class, [the _root module_](guide/bootstrapping), which is conventionally named `AppModule` and resides in a file named `app.module.ts`. You launch your app by *bootstrapping* the root NgModule.
While a small application might have only one NgModule, most apps have many more _feature modules_. The _root_ NgModule for an app is so named because it can include child NgModules in a hierarchy of any depth.
## NgModule metadata
An NgModule is defined as a class decorated with `@NgModule`. The `@NgModule` decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.
* `declarations`&mdash;The [components](guide/architecture-components), _directives_, and _pipes_ that belong to this NgModule.
* `exports`&mdash;The subset of declarations that should be visible and usable in the _component templates_ of other NgModules.
* `imports`&mdash;Other modules whose exported classes are needed by component templates declared in _this_ NgModule.
* `providers`&mdash;Creators of [services](guide/architecture-services) that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
* `bootstrap`&mdash;The main application view, called the _root component_, which hosts all other app views. Only the _root NgModule_ should set this `bootstrap` property.
Here's a simple root NgModule definition:
<code-example path="architecture/src/app/mini-app.ts" region="module" title="src/app/app.module.ts" linenums="false"></code-example>
<div class="l-sub-section">
The `export` of `AppComponent` is just to show how to export; it isn't actually necessary in this example. A root NgModule has no reason to _export_ anything because other modules don't need to _import_ the root NgModule.
</div>
## NgModules and components
NgModules provide a _compilation context_ for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
<figure>
<img src="generated/images/guide/architecture/compilation-context.png" alt="Component compilation context" class="left">
</figure>
<br class="clear">
A component and its template together define a _view_. A component can contain a _view hierarchy_, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.
<figure>
<img src="generated/images/guide/architecture/view-hierarchy.png" alt="View hierarchy" class="left">
</figure>
<br class="clear">
When you create a component, it is associated directly with a single view, called the _host view_. The host view can be the root of a view hierarchy, which can contain _embedded views_, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
<div class="l-sub-section">
The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data.
</div>
## NgModules and JavaScript modules
The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are two different and _complementary_ module systems. You can use them both to write your apps.
In JavaScript each _file_ is a module and all objects defined in the file belong to that module.
The module declares some objects to be public by marking them with the `export` key word.
Other JavaScript modules use *import statements* to access public objects from other modules.
JavaScript 中,每个*文件*是一个模块,文件中定义的所有对象都从属于那个模块。
通过 `export` 关键字,模块可以把它的某些对象声明为公共的。
其它 JavaScript 模块可以使用*import 语句*来访问这些公共对象。
<code-example path="architecture/src/app/app.module.ts" region="imports" linenums="false"></code-example>
<code-example path="architecture/src/app/app.module.ts" region="export" linenums="false"></code-example>
<div class="l-sub-section">
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
<a href="http://exploringjs.com/es6/ch_modules.html">学习更多关于 JavaScript 模块的知识。</a>
</div>
## Angular libraries
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
Angular ships as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the `@angular` prefix. Install them with the `npm` package manager and import parts of them with JavaScript `import` statements.
<br class="clear">
For example, import Angular's `Component` decorator from the `@angular/core` library like this:
例如,象下面这样,从 `@angular/core` 库中导入 `Component` 装饰器:
<code-example path="architecture/src/app/app.component.ts" region="import" linenums="false"></code-example>
You also import NgModules from Angular _libraries_ using JavaScript import statements:
还可以使用 JavaScript 的导入语句从 Angular *库*中导入 Angular *模块*
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module" linenums="false"></code-example>
In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports" linenums="false"></code-example>
In this way you're using both the Angular and JavaScript module systems _together_. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used.
<div class="l-sub-section">
Learn more from the [NgModules](guide/ngmodules) page.
更多信息,参见 [NgModules](guide/ngmodules)。
</div>
<hr/>

View File

@ -0,0 +1,48 @@
# Next steps: tools and techniques
Once you have understood the basic building blocks, you can begin to learn more about the features and tools that are available to help you develop and deliver Angular applications. Angular provides a lot more features and services that are covered in this documentation.
#### Responsive programming tools
* [Lifecycle hooks](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.
* [Observables and event processing](guide/observables): How to use observables with components and services to publish and subscribe to messages of any type, such as user-interaction events and asynchronous operation results.
#### Client-server interaction tools
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
* [Server-side Rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
* [Service Workers](guide/service-worker-intro): A service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept outgoing HTTP requests and can, for example, deliver a cached response if one is available. You can significantly improve the user experience by using a service worker to reduce dependency on the network.
#### Domain-specific libraries
* [Animations](guide/animations): Animate component behavior
without deep knowledge of animation techniques or CSS with Angular's animation library.
* [Forms](guide/forms): Support complex data entry scenarios with HTML-based validation and dirty checking.
#### Support for the development cycle
* [Testing Platform](guide/testing): Run unit tests on your application parts as they interact with the Angular framework.
* [Internationalization](guide/i18n): Angular's internationalization (i18n) tools can help you make your app available in multiple languages.
* [Compilation](guide/aot-compiler): Angular provides just-in-time (JIT) compilation for the development environment, and ahead-of-time (AOT) compilation for the production environment.
* [Security guidelines](guide/security): Learn about Angular's built-in protections against common web-app vulnerabilities and attacks such as cross-site scripting attacks.
#### Setup and deployment tools
* [Setup for local development](guide/setup): Learn how to set up a new project for development with QuickStart.
* [Installation](guide/npm-packages): The [Angular CLI](https://cli.angular.io/), Angular applications, and Angular itself depend on features and functionality provided by libraries that are available as [npm](https://docs.npmjs.com/) packages.
* [Typescript Configuration](guide/typescript-configuration): TypeScript is the primary language for Angular application development.
* [Browser support](guide/browser-support): Learn how to make your apps compatible across a wide range of browsers.
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
<hr/>

View File

@ -0,0 +1,81 @@
# Introduction to services and dependency injection
<img src="generated/images/guide/architecture/service.png" alt="Service" class="left">
_Service_ is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
<br class="clear">
Angular distinguishes components from services in order to increase modularity and reusability.
* By separating a component's view-related functionality from other kinds of processing, you can make your component classes lean and efficient. Ideally, a component's job is to enable the user experience and nothing more. It should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a _model_).
* A component should not need to define things like how to fetch data from the server, validate user input, or log directly to the console. Instead, it can delegate such tasks to services. By defining that kind of processing task in an injectable service class, you make it available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.
Angular doesn't *enforce* these principles. Angular does help you *follow* these principles by making it easy to factor your
application logic into services and make those services available to components through *dependency injection*.
## Service examples
Here's an example of a service class that logs to the browser console:
下面是一个服务类的范例,用于把日志记录到浏览器的控制台:
<code-example path="architecture/src/app/logger.service.ts" linenums="false" title="src/app/logger.service.ts (class)" region="class"></code-example>
Services can depend on other services. For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes. That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server.
<code-example path="architecture/src/app/hero.service.ts" linenums="false" title="src/app/hero.service.ts (class)" region="class"></code-example>
<hr/>
## Dependency injection
## 依赖注入dependency injection
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
Components consume services; that is, you can *inject* a service into a component, giving the component access to that service class.
To define a class as a service in Angular, use the `@Injectable` decorator to provide the metadata that allows Angular to inject it into a component as a *dependency*.
Similarly, use the `@Injectable` decorator to indicate that a component or other class (such as another service, a pipe, or an NgModule) _has_ a dependency. A dependency doesn't have to be a service&mdash;it could be a function, for example, or a value.
*Dependency injection* (often called DI) is wired into the Angular framework and used everywhere to provide new components with the services or other things they need.
* The *injector* is the main mechanism. You don't have to create an Angular injector. Angular creates an application-wide injector for you during the bootstrap process.
* The injector maintains a *container* of dependency instances that it has already created, and reuses them if possible.
* A *provider* is a recipe for creating a dependency. For a service, this is typically the service class itself. For any dependency you need in your app, you must register a provider with the app's injector, so that the injector can use it to create new instances.
When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the types of its constructor parameters. For example, the constructor of `HeroListComponent` needs a `HeroService`:
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
When Angular discovers that a component depends on a service, it first checks if the injector already has any existing instances of that service. If a requested service instance does not yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.
When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.
The process of `HeroService` injection looks something like this:
<figure>
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service" class="left">
</figure>
### Providing services
You must register at least one *provider* of any service you are going to use. You can register providers in modules or in components.
* When you add providers to the [root module](guide/architecture-modules), the same instance of a service is available to all components in your app.
<code-example path="architecture/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts (module providers)" region="providers"></code-example>
* When you register a provider at the component level, you get a new instance of the
service with each new instance of that component. At the component level, register a service provider in the `providers` property of the `@Component` metadata:
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
For more detailed information, see the [Dependency Injection](guide/dependency-injection) section.
<hr/>

View File

@ -2,912 +2,164 @@
# 架构概览
Angular is a framework for building client applications in HTML and
either JavaScript or a language like TypeScript that compiles to JavaScript.
Angular is a platform and framework for building client applications in HTML and TypeScript.
Angular is itself written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
Angular 是一个用 HTML 和 JavaScript 或者一个可以编译成 JavaScript 的语言(例如 Dart 或者 TypeScript ),来构建客户端应用的框架。
Angular 是一个用 HTML 和 JavaScript 或者一个可以编译成 JavaScript 的语言(例如 Dart 或者 TypeScript ),来构建客户端应用的平台和框架。
The framework consists of several libraries, some of them core and some optional.
The basic building blocks of an Angular application are _NgModules_, which provide a compilation context for _components_. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a _root module_ that enables bootstrapping, and typically has many more _feature modules_.
该框架包括一系列库,有些是核心库,有些是可选库。
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data. Every app has at least a root component.
You write Angular applications by composing HTML *templates* with Angularized markup,
writing *component* classes to manage those templates, adding application logic in *services*,
and boxing components and services in *modules*.
* Components use *services*, which provide specific functionality not directly related to views. Service providers can be *injected* into components as *dependencies*, making your code modular, reusable, and efficient.
你是这样编写 Angular 应用的:用 Angular 扩展语法编写 HTML *模板*
用*组件*类管理这些模板,用*服务*添加应用逻辑,
用*模块*打包发布组件与服务。
Both components and services are simply classes, with *decorators* that mark their type and provide metadata that tells Angular how to use them.
Then you launch the app by *bootstrapping* the _root module_.
Angular takes over, presenting your application content in a browser and
responding to user interactions according to the instructions you've provided.
* The metadata for a component class associates it with a *template* that defines a view. A template combines ordinary HTML with Angular *directives* and *binding markup* that allow Angular to modify the HTML before rendering it for display.
然后,你通过*引导**根模块*来启动该应用。
Angular 在浏览器中接管、展现应用的内容,并根据你提供的操作指令响应用户的交互。
* The metadata for a service class provides the information Angular needs to make it available to components through *Dependency Injection (DI)*.
Of course, there is more to it than this.
You'll learn the details in the pages that follow. For now, focus on the big picture.
当然,这只是冰山一角。后面你还会学到更多的细节。不过,目前还是先关注全景图吧。
<figure>
<img src="generated/images/guide/architecture/overview2.png" alt="overview">
</figure>
<div class="l-sub-section">
The code referenced on this page is available as a <live-example></live-example>.
本章所引用的代码见<live-example></live-example>
</div>
An app's components typically define many views, arranged hierarchically. Angular provides the `Router` service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.
## Modules
## 模块
<img src="generated/images/guide/architecture/module.png" alt="Component" class="left">
Angular defines the `NgModule`, which differs from and complements the JavaScript (ES2015) module. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
Angular apps are modular and Angular has its own modularity system called _NgModules_.
Every Angular app has a _root module_, conventionally named `AppModule`, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
Angular 应用是模块化的,并且 Angular 有自己的模块系统,它被称为 *Angular 模块*或 *NgModules*
Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the `Router` NgModule.
NgModules are a big deal.
This page introduces modules; the [NgModules](guide/ngmodules) pages
relating to NgModules covers them in detail.
NgModules 很重要。这里只是简单介绍,在 [NgModules](guide/ngmodules)中会做深入讲解。
<br class="clear">
Every Angular app has at least one NgModule class, [the _root module_](guide/bootstrapping "Bootstrapping"),
conventionally named `AppModule`.
每个 Angular 应用至少有一个模块([*根模块*](guide/bootstrapping "引导启动")),习惯上命名为 `AppModule`
While the _root module_ may be the only module in a small application, most apps have many more
_feature modules_, each a cohesive block of code dedicated to an application domain,
a workflow, or a closely related set of capabilities.
*根模块*在一些小型应用中可能是唯一的模块,大多数应用会有很多*特性模块*,每个模块都是一个内聚的代码块专注于某个应用领域、工作流或紧密相关的功能。
An NgModule, whether a _root_ or _feature_, is a class with an `@NgModule` decorator.
Angular 模块(无论是*根模块*还是*特性模块*)都是一个带有 `@NgModule` 装饰器的类。
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of _lazy-loading_&mdash;that is, loading modules on demand&mdash;in order to minimize the amount of code that needs to be loaded at startup.
<div class="l-sub-section">
Decorators are functions that modify JavaScript classes.
Angular has many decorators that attach metadata to classes so that it knows
what those classes mean and how they should work.
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">
Learn more</a> about decorators on the web.
装饰器是用来修饰 JavaScript 类的函数。
Angular 有很多装饰器,它们负责把元数据附加到类上,以了解那些类的设计意图以及它们应如何工作。
关于装饰器的<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0" target="_blank">更多信息</a>
For a more detailed discussion, see [Introduction to modules](guide/architecture-modules).
</div>
`NgModule` is a decorator function that takes a single metadata object whose properties describe the module.
The most important properties are:
`NgModule` 是一个装饰器函数,它接收一个用来描述模块属性的元数据对象。其中最重要的属性是:
* `declarations` - the _view classes_ that belong to this module.
Angular has three kinds of view classes: [components](guide/architecture#components), [directives](guide/architecture#directives), and [pipes](guide/pipes).
`declarations` - 声明本模块中拥有的*视图类*。Angular 有三种视图类:[组件](guide/architecture#components)、[指令](guide/architecture#directives)和[管道](guide/pipes)。
* `exports` - the subset of declarations that should be visible and usable in the component [templates](guide/architecture#templates) of other modules.
`exports` - declarations 的子集,可用于其它模块的组件[模板](guide/architecture#templates)。
* `imports` - other modules whose exported classes are needed by component templates declared in _this_ module.
`imports` - *本*模块声明的组件模板需要的类所在的其它模块。
* `providers` - creators of [services](guide/architecture#services) that this module contributes to
the global collection of services; they become accessible in all parts of the app.
`providers` - [服务](guide/architecture#services)的创建者,并加入到全局服务列表中,可用于应用任何部分。
* `bootstrap` - the main application view, called the _root component_,
that hosts all other app views. Only the _root module_ should set this `bootstrap` property.
`bootstrap` - 指定应用的主视图(称为*根组件*),它是所有其它视图的宿主。只有*根模块*才能设置 `bootstrap` 属性。
Here's a simple root module:
下面是一个简单的根模块:
<code-example path="architecture/src/app/mini-app.ts" region="module" title="src/app/app.module.ts" linenums="false"></code-example>
<div class="l-sub-section">
The `export` of `AppComponent` is just to show how to use the `exports` array to export a component; it isn't actually necessary in this example. A root module has no reason to _export_ anything because other components don't need to _import_ the root module.
`AppComponent``export` 语句只是用于演示如何导出的,它在这个例子中并不是必须的。根模块不需要*导出*任何东西,因为其它组件不需要导入根模块。
</div>
Launch an application by _bootstrapping_ its root module.
During development you're likely to bootstrap the `AppModule` in a `main.ts` file like this one.
通过*引导*根模块来启动应用。
在开发期间,你通常在一个 `main.ts` 文件中引导 `AppModule`,就像这样:
<code-example path="architecture/src/main.ts" title="src/main.ts" linenums="false"></code-example>
### NgModules vs. JavaScript modules
### NgModules vs. JavaScript 模块
The NgModule &mdash; a class decorated with `@NgModule` &mdash; is a fundamental feature of Angular.
NgModule一个带 `@NgModule` 装饰器的类)是 Angular 的基础特性之一。
JavaScript also has its own module system for managing collections of JavaScript objects.
It's completely different and unrelated to the NgModule system.
JavaScript 也有自己的模块系统,用来管理一组 JavaScript 对象。
它与 Angular 的模块系统完全不同且完全无关。
In JavaScript each _file_ is a module and all objects defined in the file belong to that module.
The module declares some objects to be public by marking them with the `export` key word.
Other JavaScript modules use *import statements* to access public objects from other modules.
JavaScript 中,每个*文件*是一个模块,文件中定义的所有对象都从属于那个模块。
通过 `export` 关键字,模块可以把它的某些对象声明为公共的。
其它 JavaScript 模块可以使用*import 语句*来访问这些公共对象。
<code-example path="architecture/src/app/app.module.ts" region="imports" linenums="false"></code-example>
<code-example path="architecture/src/app/app.module.ts" region="export" linenums="false"></code-example>
<div class="l-sub-section">
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
<a href="http://exploringjs.com/es6/ch_modules.html">学习更多关于 JavaScript 模块的知识。</a>
</div>
These are two different and _complementary_ module systems. Use them both to write your apps.
这两个模块化系统是不同但*互补*的,你在写程序时都会用到。
### Angular libraries
### Angular 模块库
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
Angular ships as a collection of JavaScript modules. You can think of them as library modules.
Angular 提供了一组 JavaScript 模块。可以把它们看做库模块。
Each Angular library name begins with the `@angular` prefix.
每个 Angular 库的名字都带有 `@angular` 前缀。
You install them with the **npm** package manager and import parts of them with JavaScript `import` statements.
**npm** 包管理工具安装它们,用 JavaScript 的 `import` 语句导入其中某些部件。
<br class="clear">
For example, import Angular's `Component` decorator from the `@angular/core` library like this:
例如,象下面这样,从 `@angular/core` 库中导入 `Component` 装饰器:
<code-example path="architecture/src/app/app.component.ts" region="import" linenums="false"></code-example>
You also import NgModules from Angular _libraries_ using JavaScript import statements:
还可以使用 JavaScript 的导入语句从 Angular *库*中导入 Angular *模块*
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module" linenums="false"></code-example>
In the example of the simple root module above, the application module needs material from within that `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
在上面那个简单的根模块的例子中,应用模块需要 `BrowserModule` 的某些素材。要访问这些素材,就得把它加入 `@NgModule` 元数据的 `imports` 中,就像这样:
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports" linenums="false"></code-example>
In this way you're using both the Angular and JavaScript module systems _together_.
这种情况下,你同时使用了 Angular 和 JavaScript 的模块化系统。
It's easy to confuse the two systems because they share the common vocabulary of "imports" and "exports".
Hang in there. The confusion yields to clarity with time and experience.
这两个系统比较容易混淆,因为它们共享相同的词汇 “imports” 和 “exports”。不过没关系先放一放随着时间和经验的增长自然就清楚了。
<div class="l-sub-section">
Learn more from the [NgModules](guide/ngmodules) page.
更多信息,参见 [NgModules](guide/ngmodules)。
</div>
<hr/>
## Components
## 组件
<img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left">
Every Angular application has at least one component, the *root component* that connects a component hierarchy with the page DOM. Each component defines a class that contains application data and logic, and is associated with an HTML *template* that defines a view to be displayed in a target environment.
A _component_ controls a patch of screen called a *view*.
*组件*负责控制屏幕上的一小块区域叫做*视图*。
For example, the following views are controlled by components:
例如,下列视图都是由组件控制的:
* The app root with the navigation links.
带有导航链接的应用根组件。
* The list of heroes.
英雄列表。
* The hero editor.
英雄编辑器。
You define a component's application logic&mdash;what it does to support the view&mdash;inside a class.
The class interacts with the view through an API of properties and methods.
你在类中定义组件的应用逻辑,为视图提供支持。
组件通过一些由属性和方法组成的 API 与视图交互。
{@a component-code}
For example, this `HeroListComponent` has a `heroes` property that returns an array of heroes
that it acquires from a service.
`HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.
例如,`HeroListComponent` 有一个 `heroes` 属性,它返回一个英雄数组,这个数组从一个服务获得。
`HeroListComponent` 还有一个当用户从列表中点选一个英雄时设置 `selectedHero` 属性的 `selectHero()` 方法。
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example>
Angular creates, updates, and destroys components as the user moves through the application.
Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()` declared above.
当用户在这个应用中漫游时, Angular 会创建、更新和销毁组件。
应用可以通过[生命周期钩子](guide/lifecycle-hooks)在组件生命周期的各个时间点上插入自己的操作,例如上面声明的 `ngOnInit()`
<hr/>
## Templates
## 模板
<img src="generated/images/guide/architecture/template.png" alt="Template" class="left">
You define a component's view with its companion **template**. A template is a form of HTML
that tells Angular how to render the component.
你通过组件的自带的**模板**来定义组件视图。模板以 HTML 形式存在,告诉 Angular 如何渲染组件。
A template looks like regular HTML, except for a few differences. Here is a
template for our `HeroListComponent`:
多数情况下,模板看起来很像标准 HTML当然也有一点不同的地方。下面是 `HeroListComponent` 组件的一个模板:
<code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example>
Although this template uses typical HTML elements like `<h2>` and `<p>`, it also has some differences. Code like `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>` uses Angular's [template syntax](guide/template-syntax).
模板除了可以使用像 `<h2>``<p>` 这样的典型的 HTML 元素,还能使用其它元素。
例如,像 `*ngFor``{{hero.name}}``(click)``[hero]``<app-hero-detail>` 这样的代码使用了 Angular 的[模板语法](guide/template-syntax)。
In the last line of the template, the `<app-hero-detail>` tag is a custom element that represents a new component, `HeroDetailComponent`.
在模板的最后一行,`<app-hero-detail>` 标签就是一个用来表示新组件 `HeroDetailComponent` 的自定义元素。
The `HeroDetailComponent` is a *different* component than the `HeroListComponent` you've been reviewing.
The `HeroDetailComponent` (code not shown) presents facts about a particular hero, the
hero that the user selects from the list presented by the `HeroListComponent`.
The `HeroDetailComponent` is a **child** of the `HeroListComponent`.
`HeroDetailComponent` 跟以前见到过的 `HeroListComponent` 是*不同*的组件。
`HeroDetailComponent`(代码未显示)用于展现一个特定英雄的情况,这个英雄是用户从 `HeroListComponent` 列表中选择的。
`HeroDetailComponent``HeroListComponent` 的*子组件*。
<img src="generated/images/guide/architecture/component-tree.png" alt="Metadata" class="left">
Notice how `<app-hero-detail>` rests comfortably among native HTML elements. Custom components mix seamlessly with native HTML in the same layouts.
注意到了吗?`<app-hero-detail>` 舒适地躺在原生 HTML 元素之间。
自定义组件和原生 HTML 在同一布局中融合得天衣无缝。
<hr class="clear"/>
## Metadata
## 元数据
<img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left">
Metadata tells Angular how to process a class.
元数据告诉 Angular 如何处理一个类。
<br class="clear">
[Looking back at the code](guide/architecture#component-code) for `HeroListComponent`, you can see that it's just a class.
There is no evidence of a framework, no "Angular" in it at all.
[回头看看](guide/architecture#component-code)`HeroListComponent` 就会明白:它只是一个类。
一点框架的痕迹也没有,里面完全没有出现 "Angular" 的字样。
In fact, `HeroListComponent` really is *just a class*. It's not a component until you *tell Angular about it*.
实际上,`HeroListComponent` 真的*只是一个类*。直到你*告诉 Angular* 它是一个组件。
To tell Angular that `HeroListComponent` is a component, attach **metadata** to the class.
要告诉 Angular `HeroListComponent` 是个组件,只要把**元数据**附加到这个类。
In TypeScript, you attach metadata by using a **decorator**.
Here's some metadata for `HeroListComponent`:
在 TypeScript 中,你要用**装饰器 (decorator) **来附加元数据。
下面就是 `HeroListComponent` 的一些元数据。
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example>
Here is the `@Component` decorator, which identifies the class
immediately below it as a component class.
这里看到 `@Component` 装饰器,它把紧随其后的类标记成了组件类。
The `@Component` decorator takes a required configuration object with the
information Angular needs to create and present the component and its view.
`@Component` 装饰器能接受一个配置对象, Angular 会基于这些信息创建和展示组件及其视图。
Here are a few of the most useful `@Component` configuration options:
`@Component` 的配置项包括:
* `selector`: CSS selector that tells Angular to create and insert an instance of this component
where it finds a `<app-hero-list>` tag in *parent* HTML.
For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then
Angular inserts an instance of the `HeroListComponent` view between those tags.
`selector` CSS 选择器,它告诉 Angular 在*父级* HTML 中查找 `<app-hero-list>` 标签,创建并插入该组件。
例如,如果应用的 HTML 包含 `<app-hero-list></app-hero-list>` Angular 就会把 `HeroListComponent` 的一个实例插入到这个标签中。
* `templateUrl`: module-relative address of this component's HTML template, shown [above](guide/architecture#templates).
`templateUrl`:组件 HTML 模板的模块相对地址,[如前所示](guide/architecture#templates)。
* `providers`: array of **dependency injection providers** for services that the component requires.
This is one way to tell Angular that the component's constructor requires a `HeroService`
so it can get the list of heroes to display.
`providers` - 组件所需服务的*依赖注入提供商*数组。
这是在告诉 Angular该组件的构造函数需要一个 `HeroService` 服务,这样组件就可以从服务中获得英雄数据。
<img src="generated/images/guide/architecture/template-metadata-component.png" alt="Metadata" class="left">
The metadata in the `@Component` tells Angular where to get the major building blocks you specify for the component.
`@Component` 里面的元数据会告诉 Angular 从哪里获取你为组件指定的主要的构建块。
The template, metadata, and component together describe a view.
模板、元数据和组件共同描绘出这个视图。
Apply other metadata decorators in a similar fashion to guide Angular behavior.
`@Injectable`, `@Input`, and `@Output` are a few of the more popular decorators.
其它元数据装饰器用类似的方式来指导 Angular 的行为。
例如 `@Injectable``@Input``@Output` 等是一些最常用的装饰器。
<br class="clear">
The architectural takeaway is that you must add metadata to your code
so that Angular knows what to do.
这种架构处理方式是:你向代码中添加元数据,以便 Angular 知道该怎么做。
<hr/>
## Data binding
## 数据绑定 (data binding)
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses
into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to
read as any experienced jQuery programmer can attest.
如果没有框架,你就得自己把数据值推送到 HTML 控件中,并把用户的反馈转换成动作和值更新。
如果手工写代码来实现这些推/拉逻辑,肯定会枯燥乏味、容易出错,读起来简直是噩梦 —— 写过 jQuery 的程序员大概都对此深有体会。
<img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left">
Angular supports **data binding**,
a mechanism for coordinating parts of a template with parts of a component.
Add binding markup to the template HTML to tell Angular how to connect both sides.
Angular 支持**数据绑定**,一种让模板的各部分与组件的各部分相互合作的机制。
往模板 HTML 中添加绑定标记,来告诉 Angular 如何把二者联系起来。
As the diagram shows, there are four forms of data binding syntax. Each form has a direction &mdash; to the DOM, from the DOM, or in both directions.
如图所示,数据绑定的语法有四种形式。每种形式都有一个方向 —— 绑定到 DOM 、绑定自 DOM 以及双向绑定。
<br class="clear">
The `HeroListComponent` [example](guide/architecture#templates) template has three forms:
`HeroListComponent`[示例](guide/architecture#templates)模板中有三种形式:
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example>
* The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation)
displays the component's `hero.name` property value within the `<li>` element.
`{{hero.name}}`[*插值表达式*](guide/displaying-data#interpolation)在 `<li>` 标签中显示组件的 `hero.name` 属性的值。
* The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from
the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`.
`[hero]`[*属性绑定*](guide/template-syntax#property-binding)把父组件 `HeroListComponent``selectedHero` 的值传到子组件 `HeroDetailComponent``hero` 属性中。
* The `(click)` [*event binding*](guide/user-input#click) calls the component's `selectHero` method when the user clicks a hero's name.
`(click)` [*事件绑定*](guide/user-input#click)在用户点击英雄的名字时调用组件的 `selectHero` 方法。
**Two-way data binding** is an important fourth form
that combines property and event binding in a single notation, using the `ngModel` directive.
Here's an example from the `HeroDetailComponent` template:
**双向数据绑定**是重要的第四种绑定形式,它使用 `ngModel` 指令组合了属性绑定和事件绑定的功能。
下面是 `HeroDetailComponent` 模板的范例:
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
In two-way binding, a data property value flows to the input box from the component as with property binding.
The user's changes also flow back to the component, resetting the property to the latest value,
as with event binding.
在双向绑定中,数据属性值通过属性绑定从组件流到输入框。用户的修改通过事件绑定流回组件,把属性值设置为最新的值。
Angular processes *all* data bindings once per JavaScript event cycle,
from the root of the application component tree through all child components.
Angular 在每个 JavaScript 事件循环中处理*所有的*数据绑定,它会从组件树的根部开始,递归处理全部子组件。
<figure>
<img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding">
</figure>
Data binding plays an important role in communication between a template and its component.
数据绑定在模板与对应组件的交互中扮演了重要的角色。
<figure>
<img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding">
</figure>
Data binding is also important for communication between parent and child components.
数据绑定在父组件与子组件的通讯中也同样重要。
<hr/>
## Directives
## 指令
<img src="generated/images/guide/architecture/directive.png" alt="Parent child" class="left">
Angular templates are *dynamic*. When Angular renders them, it transforms the DOM
according to the instructions given by **directives**.
Angular 模板是*动态的*。当 Angular 渲染它们时,它会根据**指令**提供的操作对 DOM 进行转换。
A directive is a class with a `@Directive` decorator.
A component is a *directive-with-a-template*;
a `@Component` decorator is actually a `@Directive` decorator extended with template-oriented features.
组件是一个*带模板的指令*`@Component` 装饰器实际上就是一个 `@Directive` 装饰器,只是扩展了一些面向模板的特性。
The `@Component` decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.
<div class="l-sub-section">
While **a component is technically a directive**,
components are so distinctive and central to Angular applications that this architectural overview separates components from directives.
Decorators are functions that modify JavaScript classes. Angular defines a number of such decorators that attach specific kinds of metadata to classes, so that it knows what those classes mean and how they should work.
虽然**严格来说组件就是一个指令**,但是组件非常独特,并在 Angular 中位于中心地位,所以在架构概览中把组件从指令中独立了出来。
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">Learn more about decorators on the web.</a>
</div>
Two *other* kinds of directives exist: _structural_ and _attribute_ directives.
### Templates, directives, and data binding
还有两种*其它*类型的指令:*结构型*指令和*属性 (attribute) 型*指令。
A template combines HTML with Angular markup that can modify the HTML elements before they are displayed.
Template *directives* provide program logic, and *binding markup* connects your application data and the document object model (DOM).
They tend to appear within an element tag as attributes do,
sometimes by name but more often as the target of an assignment or a binding.
* *Event binding* lets your app respond to user input in the target environment by updating your application data.
它们往往像属性 (attribute) 一样出现在元素标签中,
偶尔会以名字的形式出现,但多数时候还是作为赋值目标或绑定目标出现。
* *Property binding* lets you interpolate values that are computed from your application data into the HTML.
**Structural** directives alter layout by adding, removing, and replacing elements in DOM.
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports *two-way data binding*, meaning that changes in the DOM, such as user choices, can also be reflected back into your program data.
**结构型**指令通过在 DOM 中添加、移除和替换元素来修改布局。
Your templates can also use *pipes* to improve the user experience by transforming values for display. Use pipes to display, for example, dates and currency values in a way appropriate to the user's locale. Angular provides predefined pipes for common transformations, and you can also define your own.
The [example template](guide/architecture#templates) uses two built-in structural directives:
<div class="l-sub-section">
下面的[范例模板](guide/architecture#templates)中用到了两个内置的结构型指令:
For a more detailed discussion of these concepts, see [Introduction to components](guide/architecture-components).
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example>
</div>
* [`*ngFor`](guide/displaying-data#ngFor) tells Angular to stamp out one `<li>` per hero in the `heroes` list.
{@a dependency-injection}
[`*ngFor`](guide/displaying-data#ngFor)告诉 Angular 为 `heroes` 列表中的每个英雄生成一个 `<li>` 标签。
## Services and dependency injection
* [`*ngIf`](guide/displaying-data#ngIf) includes the `HeroDetail` component only if a selected hero exists.
For data or logic that is not associated with a specific view, and that you want to share across components, you create a *service* class. A service class definition is immediately preceded by the `@Injectable` decorator. The decorator provides the metadata that allows your service to be *injected* into client components as a dependency.
[`*ngIf`](guide/displaying-data#ngIf)表示只有在选择的英雄存在时,才会包含 `HeroDetail` 组件。
*Dependency injection* (or DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.
**Attribute** directives alter the appearance or behavior of an existing element.
In templates they look like regular HTML attributes, hence the name.
<div class="l-sub-section">
**属性型** 指令修改一个现有元素的外观或行为。
在模板中,它们看起来就像是标准的 HTML 属性,故名。
For a more detailed discusssion, see [Introduction to services and DI](guide/architecture-services).
The `ngModel` directive, which implements two-way data binding, is
an example of an attribute directive. `ngModel` modifies the behavior of
an existing element (typically an `<input>`)
by setting its display value property and responding to change events.
</div>
`ngModel` 指令就是属性型指令的一个例子,它实现了双向数据绑定。
`ngModel` 修改现有元素(一般是 `<input>`)的行为:设置其显示属性值,并响应 change 事件。
### Routing
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
The Angular `Router` NgModule provides a service that lets you define a navigation path among the different application states and view hierarchies in your app. It is modeled on the familiar browser navigation conventions:
Angular has a few more directives that either alter the layout structure
(for example, [ngSwitch](guide/template-syntax#ngSwitch))
or modify aspects of DOM elements and components
(for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)).
* Enter a URL in the address bar and the browser navigates to a corresponding page.
Angular 还有少量指令,它们或者修改结构布局(例如 [ngSwitch](guide/template-syntax#ngSwitch)
或者修改 DOM 元素和组件的各个方面(例如 [ngStyle](guide/template-syntax#ngStyle)和 [ngClass](guide/template-syntax#ngClass))。
在地址栏输入 URL浏览器就会导航到相应的页面。
Of course, you can also write your own directives. Components such as
`HeroListComponent` are one kind of custom directive.
* Click links on the page and the browser navigates to a new page.
当然,你也能编写自己的指令。像 `HeroListComponent` 这样的组件就是一种自定义指令
在页面中点击链接,浏览器就会导航到一个新页面。
<!-- PENDING: link to where to learn more about other kinds! -->
* Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
点击浏览器的前进和后退按钮,浏览器就会在你的浏览历史中向前或向后导航。
The router maps URL-like paths to views instead of pages. When a user performs an action, such as clicking a link, that would load a new page in the browser, the router intercepts the browser's behavior, and shows or hides view hierarchies.
If the router determines that the current application state requires particular functionality, and the module that defines it has not been loaded, the router can _lazy-load_ the module on demand.
The router interprets a link URL according to your app's view navigation rules and data state. You can navigate to new views when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. The Router logs activity in the browser's history journal, so the back and forward buttons work as well.
To define navigation rules, you associate *navigation paths* with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.
<div class="l-sub-section">
For a more detailed discussion, see [Routing and navigation](guide/router).
</div>
<hr/>
## Services
## What's next
## 服务
<img src="generated/images/guide/architecture/service.png" alt="Service" class="left">
_Service_ is a broad category encompassing any value, function, or feature that your application needs.
*服务*是一个广义范畴,包括:值、函数,或应用所需的特性。
Almost anything can be a service.
A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
几乎任何东西都可以是一个服务。
典型的服务是一个类,具有专注的、明确的用途。它应该做一件特定的事情,并把它做好。
<br class="clear">
Examples include:
例如:
* logging service
日志服务
* data service
数据服务
* message bus
消息总线
* tax calculator
税款计算器
* application configuration
应用程序配置
There is nothing specifically _Angular_ about services. Angular has no definition of a service.
There is no service base class, and no place to register a service.
服务没有什么特别属于 *Angular* 的特性。 Angular 对于服务也没有什么定义。
它甚至都没有定义服务的基类,也没有地方注册一个服务。
Yet services are fundamental to any Angular application. Components are big consumers of services.
即便如此,服务仍然是任何 Angular 应用的基础。组件就是最大的*服务*消费者。
Here's an example of a service class that logs to the browser console:
下面是一个服务类的范例,用于把日志记录到浏览器的控制台:
<code-example path="architecture/src/app/logger.service.ts" linenums="false" title="src/app/logger.service.ts (class)" region="class"></code-example>
Here's a `HeroService` that uses a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to fetch heroes.
The `HeroService` depends on the `Logger` service and another `BackendService` that handles the server communication grunt work.
下面是 `HeroService` 类,用于获取英雄数据,并通过一个已解析的[承诺 (Promise)](http://exploringjs.com/es6/ch_promises.html) 返回它们。
`HeroService` 还依赖于 `Logger` 服务和另一个用于处理服务器通讯的 `BackendService` 服务。
<code-example path="architecture/src/app/hero.service.ts" linenums="false" title="src/app/hero.service.ts (class)" region="class"></code-example>
Services are everywhere.
服务无处不在。
Component classes should be lean. They don't fetch data from the server,
validate user input, or log directly to the console.
They delegate such tasks to services.
组件类应保持精简。组件本身不从服务器获得数据、不进行验证输入,也不直接往控制台写日志。
它们把这些任务委托给服务。
A component's job is to enable the user experience and nothing more. It mediates between the view (rendered by the template)
and the application logic (which often includes some notion of a _model_).
A good component presents properties and methods for data binding.
It delegates everything nontrivial to services.
组件的任务就是提供用户体验,仅此而已。它介于视图(由模板渲染)和应用逻辑(通常包括*模型*的某些概念)之间。
设计良好的组件为数据绑定提供属性和方法,把其它琐事都委托给服务。
Angular doesn't *enforce* these principles.
It won't complain if you write a "kitchen sink" component with 3000 lines.
Angular 不会*强行保障*这些原则。
即使你花 3000 行代码写了一个“厨房洗碗槽”组件,它也不会抱怨什么。
Angular does help you *follow* these principles by making it easy to factor your
application logic into services and make those services available to components through *dependency injection*.
Angular 帮助你*遵循*这些原则 —— 它让你能轻易地把应用逻辑拆分到服务,并通过*依赖注入*来在组件中使用这些服务。
<hr/>
## Dependency injection
## 依赖注入dependency injection
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
_Dependency injection_ is a way to supply a new instance of a class
with the fully-formed dependencies it requires. Most dependencies are services.
Angular uses dependency injection to provide new components with the services they need.
“依赖注入”是提供类的新实例的一种方式,还负责处理好类所需的全部依赖。大多数依赖都是服务。
Angular 使用依赖注入来提供新组件以及组件所需的服务。
<br class="clear">
Angular can tell which services a component needs by looking at the types of its constructor parameters.
For example, the constructor of your `HeroListComponent` needs a `HeroService`:
Angular 通过查看构造函数的参数类型得知组件需要哪些服务。
例如,`HeroListComponent` 组件的构造函数需要一个 `HeroService` 服务:
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
When Angular creates a component, it first asks an **injector** for
the services that the component requires.
当 Angular 创建组件时,会首先为组件所需的服务请求一个**注入器 (injector)**。
An injector maintains a container of service instances that it has previously created.
If a requested service instance is not in the container, the injector makes one and adds it to the container
before returning the service to Angular.
When all requested services have been resolved and returned,
Angular can call the component's constructor with those services as arguments.
This is *dependency injection*.
注入器维护了一个服务实例的容器,存放着以前创建的实例。
如果所请求的服务实例不在容器中,注入器就会创建一个服务实例,并且添加到容器中,然后把这个服务返回给 Angular。
当所有请求的服务都被解析完并返回时Angular 会以这些服务为参数去调用组件的构造函数。
这就是*依赖注入* 。
The process of `HeroService` injection looks a bit like this:
`HeroService` 注入的过程差不多是这样的:
You've learned the basics about the main building blocks of an Angular application. The following diagram shows how these basic pieces are related.
<figure>
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service">
<img src="generated/images/guide/architecture/overview2.png" alt="overview">
</figure>
If the injector doesn't have a `HeroService`, how does it know how to make one?
* Together, a component and template define an Angular view.
如果注入器还没有 `HeroService`,它怎么知道该如何创建一个呢?
* A decorator on a component class adds the metadata, including a pointer to the associated template.
In brief, you must have previously registered a **provider** of the `HeroService` with the injector.
A provider is something that can create or return a service, typically the service class itself.
* Directives and binding markup in a component's template modify views based on program data and logic.
简单点说你必须先用注入器injector`HeroService` 注册一个**提供商provider**。
提供商用来创建或返回服务,通常就是这个服务类本身(相当于 `new HeroService()`)。
* The dependency injector provides services to a component, such as the router service that lets you define navigation among views.
You can register providers in modules or in components.
Each of these subjects is introduced in more detail in the following pages.
你可以在模块中或组件中注册提供商。
* [Modules](guide/architecture-modules)
In general, add providers to the [root module](guide/architecture#modules) so that
the same instance of a service is available everywhere.
* [Components](guide/architecture-components)
但通常会把提供商添加到[根模块](guide/architecture#modules)上,以便在任何地方都使用服务的同一个实例。
* [Templates](guide/architecture-components#templates-and-views)
<code-example path="architecture/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts (module providers)" region="providers"></code-example>
* [Metadata](guide/architecture-components#component-metadata)
Alternatively, register at a component level in the `providers` property of the `@Component` metadata:
* [Data binding](guide/architecture-components#data-binding)
或者,也可以在 `@Component` 元数据中的 `providers` 属性中把它注册在组件层:
* [Directives](guide/architecture-components#directives)
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
* [Pipes](guide/architecture-components#pipes)
Registering at a component level means you get a new instance of the
service with each new instance of that component.
* [Services and dependency injection](guide/architecture-services)
把它注册在组件级表示该组件的每一个新实例都会有一个服务的新实例。
<div class="l-sub-section">
<!-- We've vastly oversimplified dependency injection for this overview.
The full story is in the [dependency injection](guide/dependency-injection) page. -->
Note that the code referenced on these pages is available as a <live-example></live-example>.
<!--在这个概览中,我们过度简化了依赖注入机制。
详见[依赖注入](guide/dependency-injection)页 -->
</div>
Points to remember about dependency injection:
When you are familiar with these fundamental building blocks, you can explore them in more detail in the documentation. To learn about more tools and techniques that are available to help you build and deploy Angular applications, see [Next steps](guide/architecture-next-steps).
需要记住的关于依赖注入的要点是:
* Dependency injection is wired into the Angular framework and used everywhere.
依赖注入渗透在整个 Angular 框架中,被到处使用。
* The *injector* is the main mechanism.
**注入器 (injector)** 是本机制的核心。
* An injector maintains a *container* of service instances that it created.
注入器负责维护一个*容器*,用于存放它创建过的服务实例。
* An injector can create a new service instance from a *provider*.
注入器能使用*提供商*创建一个新的服务实例。
* A *provider* is a recipe for creating a service.
*提供商*是一个用于创建服务的配方。
* Register *providers* with injectors.
把*提供商*注册到注入器。
<hr/>
## Wrap up
## 总结
You've learned the basics about the eight main building blocks of an Angular application:
你学到的这些只是关于 Angular 应用程序的八个主要构造块的基础知识:
* [Modules](guide/architecture#modules)
[模块](guide/architecture#modules)
* [Components](guide/architecture#components)
[组件](guide/architecture#components)
* [Templates](guide/architecture#templates)
[模板](guide/architecture#templates)
* [Metadata](guide/architecture#metadata)
[元数据](guide/architecture#metadata)
* [Data binding](guide/architecture#data-binding)
[数据绑定](guide/architecture#data-binding)
* [Directives](guide/architecture#directives)
[指令](guide/architecture#directives)
* [Services](guide/architecture#services)
[服务](guide/architecture#services)
* [Dependency injection](guide/architecture#dependency-injection)
[依赖注入](guide/architecture#dependency-injection)
That's a foundation for everything else in an Angular application,
and it's more than enough to get going.
But it doesn't include everything you need to know.
这是 Angular 应用程序中所有其它东西的基础,要使用 Angular以这些作为开端就绰绰有余了。
但它仍然没有包含你需要知道的一切。
Here is a brief, alphabetical list of other important Angular features and services.
Most of them are covered in this documentation (or soon will be).
这里是一个简短的、按字母排序的列表,列出了其它重要的 Angular 特性和服务。
它们大多数已经(或即将)包括在这份开发文档中:
> [**Animations**](guide/animations): Animate component behavior
without deep knowledge of animation techniques or CSS with Angular's animation library.
> [**动画**](guide/animations):用 Angular 的动画库让组件动起来,而不需要对动画技术或 CSS 有深入的了解。
> **Change detection**: The change detection documentation will cover how Angular decides that a component property value has changed,
when to update the screen, and how it uses **zones** to intercept asynchronous activity and run its change detection strategies.
> **变更检测**:变更检测文档会告诉你 Angular 是如何决定组件的属性值变化,什么时候该更新到屏幕,
以及它是如何利用**区域 (zone)** 来拦截异步活动并执行变更检测策略。
> **Events**: The events documentation will cover how to use components and services to raise events with mechanisms for
publishing and subscribing to events.
> **事件**:事件文档会告诉你如何使用组件和服务触发支持发布和订阅的事件。
> [**Forms**](guide/forms): Support complex data entry scenarios with HTML-based validation and dirty checking.
> [**表单**](guide/forms):通过基于 HTML 的验证和脏检查机制支持复杂的数据输入场景。
> [**HTTP**](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
> [**HTTP**](guide/http):通过 HTTP 客户端,可以与服务器通讯,以获得数据、保存数据和触发服务端动作。
> [**Lifecycle hooks**](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction,
by implementing the lifecycle hook interfaces.
> [**生命周期钩子**](guide/lifecycle-hooks):通过实现生命周期钩子接口,可以切入组件生命中的几个关键点:从创建到销毁。
> [**Pipes**](guide/pipes): Use pipes in your templates to improve the user experience by transforming values for display. Consider this `currency` pipe expression:
>
> [**管道**](guide/pipes):在模板中使用管道转换成用于显示的值,以增强用户体验。例如,`currency` 管道表达式:
>
> > `price | currency:'USD':true`
>
> It displays a price of 42.33 as `$42.33`.
>
> 它把价格“42.33”显示为 `$42.33`
>
> [**Router**](guide/router): Navigate from page to page within the client
application and never leave the browser.
> [**路由器**](guide/router):在应用程序客户端的页面间导航,并且不离开浏览器。
> [**Testing**](guide/testing): Run unit tests on your application parts as they interact with the Angular framework
using the _Angular Testing Platform_.
> [**测试**](guide/testing):使用 _Angular 测试平台_,在你的应用部件与 Angular 框架交互时进行单元测试。
</div>

View File

@ -284,4 +284,4 @@ root module's `bootstrap` array.
For more on NgModules you're likely to see frequently in apps,
see [Frequently Used Modules](#).
要进一步了解常见的 NgModules 知识,参见 [关于模块的常见问题](#)。
要进一步了解常见的 NgModules 知识,参见 [关于模块的常见问题](#)。

View File

@ -416,8 +416,8 @@ Here are the features which may require additional polyfills:
[JIT compilation](guide/aot-compiler).
[JIT 编译](guide/aot-compiler)
[JIT 编译](guide/aot-compiler)
Required to reflect for metadata.
需要 reflect 来提供元数据。

View File

@ -731,8 +731,8 @@ is available to <code>declarations</code> of this module.</p>
<p><code>@Component</code> extends <code>@Directive</code>,
so the <code>@Directive</code> configuration applies to components as well</p>
<p><code>@Component</code> 继承自 <code>@Directive</code>
因此,<code>@Directive</code> 的这些配置项也同样适用于组件。</p>
<p><code>@Component</code> 继承自 <code>@Directive</code>
因此,<code>@Directive</code> 的这些配置项也同样适用于组件。</p>
</th>

View File

@ -142,33 +142,33 @@ The following code snippets illustrate how the same kind of operation is defined
<table>
<th>
<tr>
<td>
<th>
Operation
操作
</td>
</th>
<td>
<th>
Observable
可观察对象
</td>
</th>
<td>
<th>
Promise
承诺
</td>
</th>
</th>
</tr>
<tr>
@ -296,25 +296,25 @@ Here are some code samples that illustrate how the same kind of operation is def
<table>
<th>
<tr>
<td>
<th>
Observable
可观察对象
</td>
</th>
<td>
<th>
Events API
事件 API
</td>
</th>
</th>
</tr>
<tr>
@ -432,25 +432,25 @@ An observable produces values over time. An array is created as a static set of
<table>
<th>
<tr>
<td>
<th>
Observable
可观察对象
</td>
</th>
<td>
<th>
Array
数组
</td>
</th>
</th>
</tr>
<tr>

View File

@ -0,0 +1,73 @@
# Elements
## Release Status
**Angular Labs Project** - experimental and unstable. **Breaking Changes Possible**
Targeted to land in the [6.x release cycle](https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md) of Angular - subject to change
## Overview
## 概览
Elements provides an API that allows developers to register Angular Components as Custom Elements
("Web Components"), and bridges the built-in DOM API to Angular's component interface and change
detection APIs.
```ts
//hello-world.ts
import { Component, Input, NgModule } from '@angular/core';
@Component({
selector: 'hello-world',
template: `<h1>Hello {{name}}</h1>`
})
export class HelloWorld {
@Input() name: string = 'World!';
}
@NgModule({
declarations: [ HelloWorld ],
entryComponents: [ HelloWorld ]
})
export class HelloWorldModule {}
```
```ts
//app.component.ts
import { Component, NgModuleRef } from '@angular/core';
import { createNgElementConstructor } from '@angular/elements';
import { HelloWorld } from './hello-world';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(injector: Injector) {
const NgElementConstructor = createNgElementConstructor(HelloWorld, {injector});
customElements.register('hello-world', NgElementConstructor);
}
}
```
Once registered, these components can be used just like built-in HTML elements, because they *are*
HTML Elements!
They can be used in any HTML page:
```html
<hello-world name="Angular"></hello-world>
<hello-world name="Typescript"></hello-world>
```
Custom Elements are "self-bootstrapping" - they are automatically started when they are added to the
DOM, and automatically destroyed when removed from the DOM.

View File

@ -1039,11 +1039,7 @@ Callouts (like alerts) are meant to draw attention to important points. Use a ca
<div class="callout is-critical">
<header>
A critical point
</header>
<header>A critical point</header>
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix
@ -1051,11 +1047,7 @@ A critical point
<div class="callout is-important">
<header>
An important point
</header>
<header>An important point</header>
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix
@ -1063,11 +1055,7 @@ An important point
<div class="callout is-helpful">
<header>
A helpful point
</header>
<header>A helpful point</header>
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix
@ -1079,11 +1067,7 @@ Here is the markup for the first of these callouts.
<div class="callout is-critical">
<header>
A critical point
</header>
<header>A critical point</header>
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix

View File

@ -153,12 +153,12 @@ The `loadComponent()` method chooses an ad using some math.
`loadComponent()` 方法使用某种算法选择了一个广告。
First, it sets the `currentAddIndex` by taking whatever it
First, it sets the `currentAdIndex` by taking whatever it
currently is plus one, dividing that by the length of the `AdItem` array, and
using the _remainder_ as the new `currentAddIndex` value. Then, it uses that
using the _remainder_ as the new `currentAdIndex` value. Then, it uses that
value to select an `adItem` from the array.
(译注:循环选取算法)首先,它把 `currentAddIndex` 递增一,然后用它除以 `AdItem` 数组长度的*余数*作为新的 `currentAddIndex` 的值,
(译注:循环选取算法)首先,它把 `currentAdIndex` 递增一,然后用它除以 `AdItem` 数组长度的*余数*作为新的 `currentAdIndex` 的值,
最后用这个值来从数组中选取一个 `adItem`
</div>

View File

@ -279,11 +279,11 @@ You may also be interested in the following:
* [Bootstrapping](guide/bootstrapping).
[引导](guide/bootstrapping).
[引导启动](guide/bootstrapping)。
* [NgModules](guide/ngmodules).
[Angular 模块](guide/ngmodules).
[Angular 模块](guide/ngmodules).
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).

View File

@ -877,7 +877,7 @@ To implement an interceptor, declare a class that implements the `intercept()` m
Here is a do-nothing _noop_ interceptor that simply passes the request through without touching it:
这里是一个什么也不做的*空白*拦截器,它只会不做任何修改的传递这个请求。
这里是一个什么也不做的*空白*拦截器,它只会不做任何修改的传递这个请求。
<code-example
path="http/src/app/http-interceptors/noop-interceptor.ts"
@ -1194,15 +1194,15 @@ An interceptor that alters headers can be used for a number of different operati
* Authentication/authorization
认证 / 授权
认证 / 授权
* Caching behavior; for example, `If-Modified-Since`
控制缓存行为。比如 `If-Modified-Since`
控制缓存行为。比如 `If-Modified-Since`
* XSRF protection
XSRF 防护
XSRF 防护
#### Logging

View File

@ -26,19 +26,19 @@ Angular 简化了国际化工作的下列几个方面:
* Displaying dates, number, percentages, and currencies in a local format.
用本地格式显示日期、数字、百分比以及货币。
用本地格式显示日期、数字、百分比以及货币。
* Translating text in component templates.
翻译组件模板中的文本。
翻译组件模板中的文本。
* Handling plural forms of words.
处理单词的复数形式。
处理单词的复数形式。
* Handling alternative text.
处理候选文本。
处理候选文本。
This document focuses on [**Angular CLI**](https://cli.angular.io/) projects, in which the Angular
CLI generates most of the boilerplate necessary to write your app in multiple languages.
@ -143,7 +143,7 @@ The CLI imports the locale data for you when you use the parameter `--locale` wi
`ng build`.
默认情况下Angular 只包含 `en-US` 的本地化数据。如果你要把 `LOCALE_ID` 的值设置为其它地区,就必须为那个新地区导入本地化数据。
当你使用 `ng serve``ng build``--locale` 参数时CLI 会自动帮你导入相应的本地化数据。
当你使用 `ng serve``ng build``--locale` 参数时CLI 会自动帮你导入相应的本地化数据。
If you want to import locale data for other languages, you can do it manually:
@ -368,7 +368,6 @@ by the custom `id`:
你可以在 `i18n` 属性的值中使用自定义 id 与描述信息的组合。
下面的例子中,`i18n` 的属性中中就包含了一条跟在自定义 `id` 后面的描述信息:
<code-example path='i18n/doc-files/app.component.html' region='i18n-attribute-id' title='app/app.component.html' linenums="false">
</code-example>
@ -521,7 +520,7 @@ based on when the update occurred:
* The first parameter is the key. It is bound to the component property (`minutes`), which determines
the number of minutes.
第一个参数是 key。它绑定到了组件中表示分钟数的 `minutes` 属性。
第一个参数是 key。它绑定到了组件中表示分钟数的 `minutes` 属性。
* The second parameter identifies this as a `plural` translation type.
@ -674,13 +673,13 @@ If you don't use the CLI, you have two options:
* You can use the `ng-xi18n` tool directly from the `@angular/compiler-cli` package.
For more information, see [i18n in the CLI documentation](https://github.com/angular/angular-cli/wiki/xi18n).
你可以直接使用来自 `@angular/compiler-cli` 包中的 `ng-xi18n` 工具。更多信息,参见 [CLI 文档中的 i18n 部分](https://github.com/angular/angular-cli/wiki/xi18n)。
你可以直接使用来自 `@angular/compiler-cli` 包中的 `ng-xi18n` 工具。更多信息,参见 [CLI 文档中的 i18n 部分](https://github.com/angular/angular-cli/wiki/xi18n)。
* You can use the CLI Webpack plugin `AngularCompilerPlugin` from the `@ngtools/webpack` package.
Set the parameters `i18nOutFile` and `i18nOutFormat` to trigger the extraction.
For more information, see the [Angular Ahead-of-Time Webpack Plugin documentation](https://github.com/angular/angular-cli/tree/master/packages/%40ngtools/webpack).
你可以使用 CLI 中来自 `@ngtools/webpack` 包中的 Webpack 插件。设置其 `i18nOutFile``i18nOutFormat` 参数进行触发。
你可以使用 CLI 中来自 `@ngtools/webpack` 包中的 Webpack 插件。设置其 `i18nOutFile``i18nOutFormat` 参数进行触发。
更多信息,参见 [Angular AOT Webpack 插件文档](https://github.com/angular/angular-cli/tree/master/packages/%40ngtools/webpack)。
</div>
@ -697,14 +696,14 @@ Angular 的 i18n 工具支持三种翻译格式:
* XLIFF 1.2 (default)
XLIFF 1.2 (默认)
XLIFF 1.2 (默认)
* XLIFF 2
* <a href="http://cldr.unicode.org/development/development-process/design-proposals/xmb" >XML Message
Bundle (XMB)</a>
<a href="http://cldr.unicode.org/development/development-process/design-proposals/xmb" >XML 消息包 (XMB)</a>
<a href="http://cldr.unicode.org/development/development-process/design-proposals/xmb" >XML 消息包 (XMB)</a>
You can specify the translation format explicitly with the `--i18nFormat` flag as illustrated in
these example commands:
@ -875,7 +874,7 @@ This sample file is easy to translate without a special editor or knowledge of F
> This XML element represents the translation of the `<h1>` greeting tag that you marked with the
`i18n` attribute earlier in this guide.
> 这个 XML 元素表示前面你加过 `i18n` 属性的那个打招呼用的 `<h1>` 标签。
> Note that the translation unit `id=introductionHeader` is derived from the
@ -889,7 +888,7 @@ This sample file is easy to translate without a special editor or knowledge of F
and context provided by the source, description, and meaning elements to guide your selection of
the appropriate French translation.
复制 `<source/>` 标记,把它改名为 `target`,并把它的内容改为法语版的 “greeting”。
复制 `<source/>` 标记,把它改名为 `target`,并把它的内容改为法语版的 “greeting”。
如果你要做的是更复杂的翻译,可能会使用由源文本、描述信息和含义等提供的信息和上下文来给出更恰当的法语翻译。
> <code-example path="i18n/doc-files/messages.fr.xlf.html" region="translated-hello" title="src/locale/messages.fr.xlf (&lt;trans-unit&gt;, after translation)" linenums="false"></code-example>
@ -1085,7 +1084,7 @@ translation file. Provide the Angular compiler with three translation-specific p
* The locale (`fr` or `en-US` for instance).
目标地区(比如 `fr``en-US`)。
目标地区(比如 `fr``en-US`)。
The compilation process is the same whether the translation file is in `.xlf` format or in another
format that Angular understands, such as `.xtb`.
@ -1099,11 +1098,11 @@ the JIT compiler or the AOT compiler.
* With [AOT](guide/i18n#merge-aot), you pass the information as a CLI parameter.
使用[AOT](guide/i18n#merge-aot)时,用在 CLI 的参数里传入这些信息。
使用[AOT](guide/i18n#merge-aot)时,用在 CLI 的参数里传入这些信息。
* With [JIT](guide/i18n#merge-jit), you provide the information at bootstrap time.
使用[JIT](guide/i18n#merge-jit)时,在引导时提供。
使用[JIT](guide/i18n#merge-jit)时,在引导时提供。
{@a merge-aot}
@ -1133,11 +1132,11 @@ options with the `ng serve` or `ng build` commands:
* `--i18nFormat`: the format of the translation file.
`--i18nFormat`: 翻译文件的格式。
`--i18nFormat`: 翻译文件的格式。
* `--locale`: the locale id.
`--locale`: 地区的 ID。
`--locale`: 地区的 ID。
The example below shows how to serve the French language file created in previous sections of this
guide:
@ -1223,15 +1222,15 @@ the Angular compiler:
* Error: throw an error. If you are using AOT compilation, the build will fail. If you are using JIT
compilation, the app will fail to load.
Error错误抛出错误如果你使用的是 AOT 编译器,构建就会失败。如果使用的是 JIT 编译器,应用的加载就会失败。
Error错误抛出错误如果你使用的是 AOT 编译器,构建就会失败。如果使用的是 JIT 编译器,应用的加载就会失败。
* Warning (default): show a 'Missing translation' warning in the console or shell.
Warning警告 - 默认):在控制台中显示一条 “Missing translation” 警告。
Warning警告 - 默认):在控制台中显示一条 “Missing translation” 警告。
* Ignore: do nothing.
Ignore忽略什么也不做。
Ignore忽略什么也不做。
If you use the AOT compiler, specify the warning level by using the CLI parameter
`--missingTranslation`. The example below shows how to set the warning level to error:

View File

@ -12,23 +12,23 @@ A basic understanding of the following:
* [Feature Modules](guide/feature-modules).
[特性模块](guide/feature-modules).
[特性模块](guide/feature-modules)
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)
* [Frequently Used Modules](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules)
* [Types of Feature Modules](guide/module-types).
[特性模块的分类](guide/module-types).
[特性模块的分类](guide/module-types)
* [Routing and Navigation](guide/router).
[路由与导航](guide/router).
[路由与导航](guide/router)。
For the final sample app with two lazy loaded modules that this page describes, see the
<live-example></live-example>.
@ -355,15 +355,15 @@ CLI 还会把 `RouterModule.forChild(routes)` 添加到各个特性模块中。
You may also be interested in the following:
你可能对下列内容感兴趣:
你可能还会对下列内容感兴趣:
* [Routing and Navigation](guide/router).
[路由与导航](guide/router)。
[路由与导航](guide/router)。
* [Providers](guide/providers).
[服务提供商](guide/providers)。
[提供商](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -341,7 +341,7 @@ Here's a brief description of each exercise:
<th>
Component
组件
</th>

View File

@ -12,15 +12,15 @@ A basic understanding of the following concepts:
* [Feature Modules](guide/feature-modules).
[特性模块](guide/feature-modules)
[特性模块](guide/feature-modules)
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
* [Frequently Used Modules](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules)。
[常用模块](guide/frequent-ngmodules)。
<hr>
@ -31,23 +31,23 @@ tend to fall into the following groups:
* Domain feature modules.
领域特性模块。
领域特性模块。
* Routed feature modules.
带路由的特性模块。
带路由的特性模块。
* Routing modules.
路由模块。
路由模块。
* Service feature modules.
服务特性模块
服务特性模块
* Widget feature modules.
可视部件特性模块。
可视部件特性模块。
While the following guidelines describe the use of each type and their
typical characteristics, in real world apps, you may see hybrids.
@ -122,7 +122,7 @@ typical characteristics, in real world apps, you may see hybrids.
Routed
路由
路由
</td>
@ -206,7 +206,7 @@ typical characteristics, in real world apps, you may see hybrids.
路由模块应该与其伴随模块同名但是加上“Routing”后缀。比如<code>foo.module.ts</code> 中的 <code>FooModule</code> 就有一个位于 <code>foo-routing.module.ts</code> 文件中的 <code>FooRoutingModule</code> 路由模块。
如果其伴随模块是根模块 `AppModule``AppRoutingModule` 就要使用 `RouterModule.forRoot(routes)` 来把路由器配置添加到它的 `imports` 中。
所有其它路由模块都是子模块,要使用 `RouterModule.forChild(routes)`
所有其它路由模块都是子模块,要使用 `RouterModule.forChild(routes)`
</li>
@ -570,11 +570,11 @@ The following table summarizes the key characteristics of each feature module gr
You may also be interested in the following:
你可能还对下列内容感兴趣:
你可能还对下列内容感兴趣:
* [Lazy Loading Modules with the Angular Router](guide/lazy-loading-ngmodules).
[使用 Angular 路由器惰性加载模块](guide/lazy-loading-ngmodules)。
[使用 Angular 路由器惰性加载模块](guide/lazy-loading-ngmodules)。
* [Providers](guide/providers).

View File

@ -10,11 +10,11 @@ A basic understanding of the following concepts:
* [Bootstrapping](guide/bootstrapping).
[引导](guide/bootstrapping)。
[引导启动](guide/bootstrapping)。
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
<hr />
@ -32,15 +32,15 @@ into three categories:
* **Static:** Compiler configuration which tells the compiler about directive selectors and where in templates the directives should be applied through selector matching. This is configured via the `declarations` array.
**静态的:**编译器配置,用于告诉编译器指令的选择器并通过选择器匹配的方式决定要把该指令应用到模板中的什么位置。它是通过 `declarations` 数组来配置的。
**静态的:**编译器配置,用于告诉编译器指令的选择器并通过选择器匹配的方式决定要把该指令应用到模板中的什么位置。它是通过 `declarations` 数组来配置的。
* **Runtime:** Injector configuration via the `providers` array.
**运行时:**通过 `providers` 数组提供给注入器的配置。
**运行时:**通过 `providers` 数组提供给注入器的配置。
* **Composability/Grouping:** Bringing NgModules together and making them available via the `imports` and `exports` arrays.
**组合/分组:**通过 `imports``exports` 数组来把多个 NgModule 放在一起,并彼此可用。
**组合/分组:**通过 `imports``exports` 数组来把多个 NgModule 放在一起,并彼此可用。
```typescript
@ -309,7 +309,7 @@ The following table summarizes the `@NgModule` metadata properties.
<td>
A list of components that are automatically bootstrapped.
要自动启动的组件列表。
Usually there's only one component in this list, the _root component_ of the application.
@ -340,7 +340,7 @@ The following table summarizes the `@NgModule` metadata properties.
<td>
A list of components that can be dynamically loaded into the view.
那些可以动态加载进视图的组件列表。
By default, an Angular app always has at least one entry component, the root component, `AppComponent`. Its purpose is to serve as a point of entry into the app, that is, you bootstrap it to launch the app.
@ -394,15 +394,15 @@ You may also be interested in the following:
* [Feature Modules](guide/feature-modules).
[特性模块](guide/feature-modules)
[特性模块](guide/feature-modules)
* [Entry Components](guide/entry-components).
[入口组件](guide/entry-components)
[入口组件](guide/entry-components)
* [Providers](guide/providers).
[提供商](guide/providers)。
[提供商](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -12,6 +12,8 @@ A basic understanding of the following concepts:
* [NgModules](guide/ngmodules).
[Angular 模块](guide/ngmodules).
<hr />
NgModules help organize an application into cohesive blocks of functionality.

View File

@ -57,7 +57,7 @@ NgModule 是一些带有 `@NgModule` 装饰器的类。`@NgModule` 装饰器的
The `AppModule` generated from the Angular CLI demonstrates both kinds of modules in action:
Angular CLI 生成的 `AppModule` 实际演示了这两种模块:
Angular CLI 生成的 `AppModule` 实际演示了这两种模块:
```typescript
@ -94,7 +94,7 @@ Declarables are the only classes that matter to the [Angular compiler](guide/ngm
* Instead of defining all member classes in one giant file as in a JavaScript module,
you list the module's classes in the `@NgModule.declarations` list.
与 JavaScript 类把它所有的成员类都放在一个巨型文件中不同,你要把该模块的类列在它的 `@NgModule.declarations` 列表中。
与 JavaScript 类把它所有的成员类都放在一个巨型文件中不同,你要把该模块的类列在它的 `@NgModule.declarations` 列表中。
* An NgModule can only export the [declarable classes](guide/ngmodule-faq#q-declarable)
it owns or imports from other modules. It doesn't declare or export any other kind of class.
@ -104,7 +104,7 @@ it owns or imports from other modules. It doesn't declare or export any other ki
* Unlike JavaScript modules, an NgModule can extend the _entire_ application with services
by adding providers to the `@NgModule.providers` list.
与 JavaScript 模块不同NgModule 可以通过把服务提供商加到 `@NgModule.providers` 列表中,来用服务扩展*整个*应用。
与 JavaScript 模块不同NgModule 可以通过把服务提供商加到 `@NgModule.providers` 列表中,来用服务扩展*整个*应用。
<hr />
@ -118,11 +118,11 @@ For more information on NgModules, see:
* [Bootstrapping](guide/bootstrapping).
[引导](guide/bootstrapping).
[引导启动](guide/bootstrapping)。
* [Frequently used modules](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules)
* [Providers](guide/providers).

View File

@ -12,11 +12,11 @@ A basic understanding of the following concepts:
* [Bootstrapping](guide/bootstrapping).
[引导启动](guide/bootstrapping)。
[引导启动](guide/bootstrapping)。
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
<hr>
@ -83,19 +83,19 @@ NgModule 的元数据会做这些:
* Declares which components, directives, and pipes belong to the module.
声明某些组件、指令和管道属于这个模块。
声明某些组件、指令和管道属于这个模块。
* Makes some of those components, directives, and pipes public so that other module's component templates can use them.
公开其中的部分组件、指令和管道,以便其它模块中的组件模板中可以使用它们。
公开其中的部分组件、指令和管道,以便其它模块中的组件模板中可以使用它们。
* Imports other modules with the components, directives, and pipes that components in the current module need.
导入其它带有组件、指令和管道的模块,这些模块中的元件都是本模块所需的。
导入其它带有组件、指令和管道的模块,这些模块中的元件都是本模块所需的。
* Provides services that the other application components can use.
提供一些供应用中的其它组件使用的服务。
提供一些供应用中的其它组件使用的服务。
Every Angular app has at least one module, the root module.
You [bootstrap](guide/bootstrapping) that module to launch the application.
@ -141,15 +141,15 @@ You may also be interested in the following:
* [Feature Modules](guide/feature-modules).
[特性模块](guide/feature-modules)
[特性模块](guide/feature-modules)
* [Entry Components](guide/entry-components).
[入口组件](guide/entry-components)
[入口组件](guide/entry-components)
* [Providers](guide/providers).
[服务提供商](guide/providers).
[提供商](guide/providers)。
* [Types of NgModules](guide/module-types).

View File

@ -80,7 +80,7 @@ The *devDependencies* are only necessary to *develop* the application.
{@a dependencies}
## *dependencies*
## *Dependencies*
The `dependencies` section of `package.json` contains:
@ -193,7 +193,7 @@ which polyfills missing features for several popular browser.
{@a dev-dependencies}
## *devDependencies*
## *DevDependencies*
The packages listed in the *devDependencies* section of the `package.json` help you develop the application on your local machine.

View File

@ -8,15 +8,15 @@ Angular 使用可观察对象作为处理各种常用异步操作的接口。比
* The `EventEmitter` class extends `Observable`.
`EventEmitter` 类派生自 `Observable`
`EventEmitter` 类派生自 `Observable`
* The HTTP module uses observables to handle AJAX requests and responses.
HTTP 模块使用可观察对象来处理 AJAX 请求和响应。
HTTP 模块使用可观察对象来处理 AJAX 请求和响应。
* The Router and Forms modules use observables to listen for and respond to user-input events.
路由器和表单模块使用可观察对象来监听对用户输入事件的响应。
路由器和表单模块使用可观察对象来监听对用户输入事件的响应。
## Event emitter
@ -46,19 +46,19 @@ Angular 的 `HttpClient` 从 HTTP 方法调用中返回了可观察对象。例
* Observables do not mutate the server response (as can occur through chained `.then()` calls on promises). Instead, you can use a series of operators to transform values as needed.
可观察对象不会修改服务器的响应(和在承诺上串联起来的 `.then()` 调用一样)。反之,你可以使用一系列操作符来按需转换这些值。
可观察对象不会修改服务器的响应(和在承诺上串联起来的 `.then()` 调用一样)。反之,你可以使用一系列操作符来按需转换这些值。
* HTTP requests are cancellable through the `unsubscribe()` method.
HTTP 请求是可以通过 `unsubscribe()` 方法来取消的。
HTTP 请求是可以通过 `unsubscribe()` 方法来取消的。
* Requests can be configured to get progress event updates.
请求可以进行配置,以获取进度事件的变化。
请求可以进行配置,以获取进度事件的变化。
* Failed requests can be retried easily.
失败的请求很容易重试。
失败的请求很容易重试。
## Async pipe

View File

@ -79,11 +79,11 @@ An `Observable` instance begins publishing values only when someone subscribes t
* `Observable.of(...items)`&mdash;Returns an `Observable` instance that synchronously delivers the values provided as arguments.
`Observable.of(...items)` —— 返回一个 `Observable` 实例,它用同步的方式把参数中提供的这些值发送出来。
`Observable.of(...items)` —— 返回一个 `Observable` 实例,它用同步的方式把参数中提供的这些值发送出来。
* `Observable.from(iterable)`&mdash;Converts its argument to an `Observable` instance. This method is commonly used to convert an array to an observable.
`Observable.from(iterable)` —— 把它的参数转换成一个 `Observable` 实例。
`Observable.from(iterable)` —— 把它的参数转换成一个 `Observable` 实例。
该方法通常用于把一个数组转换成一个(发送多个值的)可观察对象。
</div>

View File

@ -16,23 +16,23 @@ Observables can simplify the implementation of type-ahead suggestions. Typically
* Listen for data from an input.
从输入中监听数据。
从输入中监听数据。
* Trim the value (remove whitespace) and make sure its a minimum length.
移除输入值前后的空白字符,并确认它达到了最小长度。
移除输入值前后的空白字符,并确认它达到了最小长度。
* Debounce (so as not to send off API requests for every keystroke, but instead wait for a break in keystrokes).
防抖(这样才能防止连续按键时每次按键都发起 API 请求,而应该等到按键出现停顿时才发起)
防抖(这样才能防止连续按键时每次按键都发起 API 请求,而应该等到按键出现停顿时才发起)
* Dont send a request if the value stays the same (rapidly hit a character, then backspace, for instance).
如果输入值没有变化,则不要发起请求(比如按某个字符,然后快速按退格)。
如果输入值没有变化,则不要发起请求(比如按某个字符,然后快速按退格)。
* Cancel ongoing AJAX requests if their results will be invalidated by the updated results.
如果已发出的 AJAX 请求的结果会因为后续的修改而变得无效,那就取消它。
如果已发出的 AJAX 请求的结果会因为后续的修改而变得无效,那就取消它。
Writing this in full JavaScript can be quite involved. With observables, you can use a simple series of RxJS operators:

View File

@ -8,11 +8,11 @@
* A basic understanding of [Bootstrapping](guide/bootstrapping).
对[引导](guide/bootstrapping)有基本的了解。
对[引导](guide/bootstrapping)有基本的了解。
* Familiarity with [Frequently Used Modules](guide/frequent-ngmodules).
熟悉[常用模块](guide/frequent-ngmodules).
熟悉[常用模块](guide/frequent-ngmodules).
For the final sample app using the provider that this page describes,
see the <live-example></live-example>.
@ -136,11 +136,11 @@ You may also be interested in:
* [Singleton Services](guide/singleton-services), which elaborates on the concepts covered on this page.
[单例服务](guide/singleton-services)详细解释了本页包含的那些概念。
[单例服务](guide/singleton-services)详细解释了本页包含的那些概念。
* [Lazy Loading Modules](guide/lazy-loading-ngmodules).
[惰性加载模块](guide/lazy-loading-ngmodules)
[惰性加载模块](guide/lazy-loading-ngmodules).
* [NgModule FAQ](guide/ngmodule-faq).

View File

@ -137,9 +137,9 @@ You can find it in `./src/app/app.component.ts`.
它就是名叫 `app-root` 的*根组件*。
你可以在 `./src/app/app.component.ts` 目录下找到它。
Open the component file and change the `title` property from _Welcome to app!!_ to _Welcome to My First Angular App!!_:
Open the component file and change the `title` property from `'app'` to `'My First Angular App!'`.
打开这个组件文件,并且把 `title` 属性从 _Welcome to app!!_ 改为 _Welcome to My First Angular App!!_
打开这个组件文件,并且把 `title` 属性从 `'app'` 改为 `'My First Angular App!'`
<code-example path="cli-quickstart/src/app/app.component.ts" region="title" title="src/app/app.component.ts" linenums="false"></code-example>

File diff suppressed because it is too large Load Diff

View File

@ -12,23 +12,23 @@ RxJS 提供了一种对 `Observable` 类型的实现,直到 `Observable` 成
* Converting existing code for async operations into observables
把现有的异步代码转换成可观察对象
把现有的异步代码转换成可观察对象
* Iterating through the values in a stream
迭代流中的各个值
迭代流中的各个值
* Mapping values to different types
把这些值映射成其它类型
把这些值映射成其它类型
* Filtering streams
对流进行过滤
对流进行过滤
* Composing multiple streams
组合多个流
组合多个流
## Observable creation functions

View File

@ -16,7 +16,7 @@ A basic understanding of the following:
* [Getting Started with Service Workers](guide/service-worker-getting-started).
[Service Worker 快速起步](guide/service-worker-getting-started).
[Service Worker 快速起步](guide/service-worker-getting-started).
<hr />
@ -34,19 +34,19 @@ The `SwUpdate` service supports four separate operations:
* Getting notified of *available* updates. These are new versions of the app to be loaded if the page is refreshed.
获取出现*可用*更新的通知。如果要刷新页面,这些就是可加载的新版本。
获取出现*可用*更新的通知。如果要刷新页面,这些就是可加载的新版本。
* Getting notified of update *activation*. This is when the service worker starts serving a new version of the app immediately.
获取更新*被激活*的通知。这时候 Service Worker 就可以立即使用这些新版本提供服务了。
获取更新*被激活*的通知。这时候 Service Worker 就可以立即使用这些新版本提供服务了。
* Asking the service worker to check the server for new updates.
要求 Service Worker 向服务器查询是否有新版本。
要求 Service Worker 向服务器查询是否有新版本。
* Asking the service worker to activate the latest version of the app for the current tab.
要求 Service Worker 为当前页面激活该应用的最新版本。
要求 Service Worker 为当前页面激活该应用的最新版本。
### Available and activated updates
@ -97,7 +97,7 @@ Doing this could break lazy-loading into currently running apps, especially if t
## More on Angular service workers
## 关于 Angular Service Worker 的更多知识
## 关于 Angular Service Worker 的更多信息
You may also be interested in the following:

View File

@ -14,7 +14,7 @@ A basic understanding of the following:
* [Service Worker in Production](guide/service-worker-devops).
[产品环境下的 Service Worker](guide/service-worker-devops).
[产品环境下的 Service Worker](guide/service-worker-devops).
<hr />
@ -44,15 +44,15 @@ Patterns use a limited glob format:
* `**` matches 0 or more path segments.
`**` 匹配 0 到多段路径。
`**` 匹配 0 到多段路径。
* `*` matches exactly one path segment or filename segment.
`*` 只匹配一段路径或文件名。
`*` 只匹配一段路径或文件名。
* The `!` prefix marks the pattern as being negative, meaning that only files that don't match the pattern will be included.
`!` 前缀表示该模式是反的,也就是说只包含与该模式不匹配的文件。
`!` 前缀表示该模式是反的,也就是说只包含与该模式不匹配的文件。
Example patterns:
@ -60,15 +60,15 @@ Example patterns:
* `/**/*.html` specifies all HTML files.
`/**/*.html` 指定所有 HTML 文件。
`/**/*.html` 指定所有 HTML 文件。
* `/*.html` specifies only HTML files in the root.
`/*.html` 仅指定根目录下的 HTML 文件。
`/*.html` 仅指定根目录下的 HTML 文件。
* `!/**/*.map` exclude all sourcemaps.
`!/**/*.map` 排除了所有源码映射文件。
`!/**/*.map` 排除了所有源码映射文件。
Each section of the configuration file is described below.
@ -151,12 +151,12 @@ The `installMode` determines how these resources are initially cached. The `inst
* `prefetch` tells the Angular service worker to fetch every single listed resource while it's caching the current version of the app. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline.
`prefetch` 告诉 Angular Service Worker 在缓存当前版本的应用时要获取每一个列出的资源。
`prefetch` 告诉 Angular Service Worker 在缓存当前版本的应用时要获取每一个列出的资源。
这是个带宽密集型的模式,但可以确保这些资源在请求时可用,即使浏览器正处于离线状态。
* `lazy` does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested will not be cached. This is useful for things like images at different resolutions, so the service worker only caches the correct assets for the particular screen and orientation.
`lazy` 不会预先缓存任何资源。相反Angular Service Worker 只会缓存它收到请求的资源。
`lazy` 不会预先缓存任何资源。相反Angular Service Worker 只会缓存它收到请求的资源。
这是一种按需缓存模式。永远不会请求的资源也永远不会被缓存。
这对于像为不同分辨率提供的图片之类的资源很有用,那样 Service Worker 就只会为特定的屏幕和设备方向缓存正确的资源。
@ -169,11 +169,11 @@ For resources already in the cache, the `updateMode` determines the caching beha
* `prefetch` tells the service worker to download and cache the changed resources immediately.
`prefetch` 会告诉 Service Worker 立即下载并缓存更新过的资源。
`prefetch` 会告诉 Service Worker 立即下载并缓存更新过的资源。
* `lazy` tells the service worker to not cache those resources. Instead, it treats them as unrequested and waits until they're requested again before updating them. An `updateMode` of `lazy` is only valid if the `installMode` is also `lazy`.
`lazy` 告诉 Service Worker 不要缓存这些资源,而是先把它们看作未被请求的,等到它们再次被请求时才进行更新。
`lazy` 告诉 Service Worker 不要缓存这些资源,而是先把它们看作未被请求的,等到它们再次被请求时才进行更新。
`lazy` 这个 `updateMode` 只有在 `installMode` 也同样是 `lazy` 时才有效。
### `resources`
@ -184,16 +184,16 @@ This section describes the resources to cache, broken up into three groups.
* `files` lists patterns that match files in the distribution directory. These can be single files or glob-like patterns that match a number of files.
`files` 列出了与 `dist` 目录中的文件相匹配的模式。它们可以是单个文件也可以是能匹配多个文件的类似 glob 的模式。
`files` 列出了与 `dist` 目录中的文件相匹配的模式。它们可以是单个文件也可以是能匹配多个文件的类似 glob 的模式。
* `versionedFiles` is like `files` but should be used for build artifacts that already include a hash in the filename, which is used for cache busting. The Angular service worker can optimize some aspects of its operation if it can assume file contents are immutable.
`versionedFiles``files` 相似,但是它用来对工件进行构建,这些工件已经在文件名中包含了一个散列,用于让其缓存失效。
`versionedFiles``files` 相似,但是它用来对工件进行构建,这些工件已经在文件名中包含了一个散列,用于让其缓存失效。
如果 Angular Service Worker 能假定这些文件在文件名不变时其内容也不会变,那它就可以从某些方面优化这种操作。
* `urls` includes both URLs and URL patterns that will be matched at runtime. These resources are not fetched directly and do not have content hashes, but they will be cached according to their HTTP headers. This is most useful for CDNs such as the Google Fonts service.
`urls` 包括要在运行时进行匹配的 URL 和 URL 模式。
`urls` 包括要在运行时进行匹配的 URL 和 URL 模式。
这些资源不是直接获取的,也没有内容散列,但它们会根据 HTTP 标头进行缓存。
这对于像 Google Fonts 服务这样的 CDN 非常有用。
@ -271,23 +271,23 @@ This section defines the policy by which matching requests will be cached.
* `d`: days
`d`:天数
`d`:天数
* `h`: hours
`h`:小时数
`h`:小时数
* `m`: minutes
`m`:分钟数
`m`:分钟数
* `s`: seconds
`s`:秒数
`s`:秒数
* `u`: milliseconds
`u`:微秒数
`u`:微秒数
For example, the string `3d12h` will cache content for up to three and a half days.
@ -308,7 +308,7 @@ Angular Service Worker 可以使用两种缓存策略之一来获取数据资源
* `performance`, the default, optimizes for responses that are as fast as possible. If a resource exists in the cache, the cached version is used. This allows for some staleness, depending on the `maxAge`, in exchange for better performance. This is suitable for resources that don't change often; for example, user avatar images.
`performance`,默认值,为尽快给出响应而优化。如果缓存中存在某个资源,则使用这个缓存版本。
`performance`,默认值,为尽快给出响应而优化。如果缓存中存在某个资源,则使用这个缓存版本。
它允许资源有一定的陈旧性(取决于 `maxAge`)以换取更好的性能。适用于那些不经常改变的资源,例如用户头像。
* `freshness` optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to `timeout`, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances.

View File

@ -17,7 +17,7 @@ A basic understanding of the following:
* [Service Worker Communication](guide/service-worker-communications).
[与 Service Worker 通讯](guide/service-worker-communications).
[与 Service Worker 通讯](guide/service-worker-communications).
<hr />
@ -135,15 +135,15 @@ Hash mismatches can occur for a variety of reasons:
* Caching layers in between the origin server and the end user could serve stale content.
在源服务器和最终用户之间缓存图层可能会提供陈旧的内容。
在源服务器和最终用户之间缓存图层可能会提供陈旧的内容。
* A non-atomic deployment could result in the Angular service worker having visibility of partially updated content.
非原子化的部署可能会导致 Angular Service Worker 看到部分更新后的内容。
非原子化的部署可能会导致 Angular Service Worker 看到部分更新后的内容。
* Errors during the build process could result in updated resources without `ngsw.json` being updated. The reverse could also happen resulting in an updated `ngsw.json` without updated resources.
构建过程中的错误可能会导致更新了资源,却没有更新 `ngsw.json`
构建过程中的错误可能会导致更新了资源,却没有更新 `ngsw.json`
反之,也可能发生没有更新资源,却更新了 `ngsw.json` 的情况。
#### Unhashed content
@ -217,11 +217,11 @@ Angular Service Worker 为什么可能会更改运行中的应用的版本有几
* The current version becomes invalid due to a failed hash.
由于哈希验证失败,当前版本变成了无效的。
由于哈希验证失败,当前版本变成了无效的。
* An unrelated error causes the service worker to enter safe mode; that is, temporary deactivation.
某个无关的错误导致 Service Worker 进入了安全模式,或者说,它被暂时禁用了。
某个无关的错误导致 Service Worker 进入了安全模式,或者说,它被暂时禁用了。
The Angular service worker is aware of which versions are in
use at any given moment and it cleans up versions when
@ -237,11 +237,11 @@ of a running app are normal events:
* The page is reloaded/refreshed.
页面被重新加载/刷新。
页面被重新加载/刷新。
* The page requests an update be immediately activated via the `SwUpdate` service.
该页面通过 `SwUpdate` 服务请求立即激活这个更新。
该页面通过 `SwUpdate` 服务请求立即激活这个更新。
### Service worker updates
@ -345,7 +345,7 @@ clean copy of the latest known version of the app. Older cached
versions are safe to use, so existing tabs continue to run from
cache, but new loads of the app will be served from the network.
`EXISTING_CLIENTS_ONLY`:这个 Service Worker 没有该应用的最新已知版本的干净副本。
`EXISTING_CLIENTS_ONLY`:这个 Service Worker 没有该应用的最新已知版本的干净副本。
较旧的缓存版本可以被安全的使用,所以现有的选项卡将继续使用较旧的版本运行本应用,
但新的应用将从网络上加载。
@ -354,7 +354,7 @@ using cached data. Either an unexpected error occurred or all
cached versions are invalid. All traffic will be served from the
network, running as little service worker code as possible.
`SAFE_MODE`Service Worker 不能保证使用缓存数据的安全性。
`SAFE_MODE`Service Worker 不能保证使用缓存数据的安全性。
发生了意外错误或所有缓存版本都无效。
这时所有的流量都将从网络提供,尽量少运行 Service Worker 中的代码。
@ -481,13 +481,13 @@ Chrome 等浏览器提供了能与 Service Worker 交互的开发者工具。
in the background and never restarts. This can cause behavior with Dev
Tools open to differ from behavior a user might experience.
使用开发人员工具时Service Worker 将继续在后台运行,并且不会重新启动。
使用开发人员工具时Service Worker 将继续在后台运行,并且不会重新启动。
这可能会导致开着 Dev Tools 时的行为与用户实际遇到的行为不一样。
* If you look in the Cache Storage viewer, the cache is frequently
out of date. Right click the Cache Storage title and refresh the caches.
如果你查看缓存存储器的查看器,缓存就会经常过期。右键单击缓存存储器的标题并刷新缓存。
如果你查看缓存存储器的查看器,缓存就会经常过期。右键单击缓存存储器的标题并刷新缓存。
Stopping and starting the service worker in the Service Worker
pane triggers a check for updates.
@ -553,7 +553,7 @@ the past on your site.
## More on Angular service workers
## 关于 Angular Service Worker 的更多知识
## 关于 Angular Service Worker 的更多信息
You may also be interested in the following:

View File

@ -12,7 +12,7 @@ A basic understanding of the following:
* [Introduction to Angular service workers](guide/service-worker-intro).
[Angular Service Worker 简介](guide/service-worker-intro).
[Angular Service Worker 简介](guide/service-worker-intro).
<hr />
@ -272,11 +272,11 @@ Notice that all of the files the browser needs to render this application are ca
* Build artifacts (JS and CSS bundles).
构建结果JS 和 CSS 包)。
构建结果JS 和 CSS 包)。
* Anything under `assets`.
`assets` 下的所有文件。
`assets` 下的所有文件。
### Making changes to your application
@ -363,7 +363,7 @@ Service Worker *在后台*安装好了这个更新后的版本,下次加载或
## More on Angular service workers
## 关于 Angular Service Worker 的更多知识
## 关于 Angular Service Worker 的更多信息
You may also be interested in the following:

View File

@ -47,23 +47,23 @@ Angular 的 Service Worker 的行为遵循下列设计目标:
* Caching an application is like installing a native application. The application is cached as one unit, and all files update together.
像安装原生应用一样缓存应用。该应用作为整体被缓存,它的所有文件作为整体进行更新。
像安装原生应用一样缓存应用。该应用作为整体被缓存,它的所有文件作为整体进行更新。
* A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.
正在运行的应用使用所有文件的同一版本继续运行。不要突然开始接收来自新版本的、可能不兼容的缓存文件。
正在运行的应用使用所有文件的同一版本继续运行。不要突然开始接收来自新版本的、可能不兼容的缓存文件。
* When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.
当用户刷新本应用时,他们会看到最新的被完全缓存的版本。新的页标签中会加载最新的缓存代码。
当用户刷新本应用时,他们会看到最新的被完全缓存的版本。新的页标签中会加载最新的缓存代码。
* Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.
在更改发布之后,相对较快的在后台进行更新。在一次完整的更新完成之前,仍然使用应用的上一个版本。
在更改发布之后,相对较快的在后台进行更新。在一次完整的更新完成之前,仍然使用应用的上一个版本。
* The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.
只要有可能Service Worker 就会尽量节省带宽。它只会下载那些发生了变化的资源。
只要有可能Service Worker 就会尽量节省带宽。它只会下载那些发生了变化的资源。
To support these behaviors, the Angular service worker loads a *manifest* file from the server. The manifest describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a user-provided configuration file called `ngsw-config.json`, by using a build tool such as the Angular CLI.
@ -88,11 +88,11 @@ To use Angular service workers, you must have the following Angular and CLI vers
* Angular 5.0.0 or later.
Angular 5.0.0 或更高。
Angular 5.0.0 或更高。
* Angular CLI 1.6.0 or later.
Angular CLI 1.6.0 或更高。
Angular CLI 1.6.0 或更高。
Your application must run in a web browser that supports service workers. Currently, the latest versions of Chrome and Firefox are supported. To learn about other browsers that are service worker ready, see the [Can I Use](http://caniuse.com/#feat=serviceworkers) page.
@ -122,7 +122,7 @@ The remainder of this Angular documentation specifically addresses the Angular i
You may also be interested in the following:
你可能还对下列内容感兴趣:
你可能还对下列内容感兴趣:
* [Getting Started with service workers](guide/service-worker-getting-started).

View File

@ -12,23 +12,23 @@ A basic understanding of the following:
* [Feature Modules](guide/feature-modules).
[特性模块](guide/feature-modules).
[特性模块](guide/feature-modules)
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
[JavaScript 模块与 NgModules](guide/ngmodule-vs-jsmodule)。
* [Frequently Used Modules](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules).
[常用模块](guide/frequent-ngmodules)
* [Routing and Navigation](guide/router).
[路由与导航](guide/router).
[路由与导航](guide/router)。
* [Lazy loading modules](guide/lazy-loading-ngmodules).
[惰性加载模块](guide/lazy-loading-ngmodules).
[惰性加载模块](guide/lazy-loading-ngmodules).
<!--* Components (#TBD) We dont have a page just on the concept of components, but I think one would be helpful for beginners.-->
@ -69,15 +69,15 @@ Note the following:
* It imports the `CommonModule` because the module's component needs common directives.
它导入了 `CommonModule`,因为该模块需要一些常用指令。
它导入了 `CommonModule`,因为该模块需要一些常用指令。
* It declares and exports the utility pipe, directive, and component classes.
它声明并导出了一些工具性的管道、指令和组件类。
它声明并导出了一些工具性的管道、指令和组件类。
* It re-exports the `CommonModule` and `FormsModule`.
它重新导出了 `CommonModule``FormsModule`
它重新导出了 `CommonModule``FormsModule`
By re-exporting `CommonModule` and `FormsModule`, any other module that imports this
`SharedModule`, gets access to directives like `NgIf` and `NgFor` from `CommonModule`
@ -123,11 +123,11 @@ To read about sharing services, see [Providers](guide/providers).
You may also be interested in the following:
你可能还对下列内容感兴趣:
你可能还对下列内容感兴趣:
* [Providers](guide/providers).
[服务提供商](guide/providers).
[提供商](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -8,11 +8,11 @@
* A basic understanding of [Bootstrapping](guide/bootstrapping).
对[引导](guide/bootstrapping)有基本的了解。
对[引导](guide/bootstrapping)有基本的了解。
* Familiarity with [Providers](guide/providers).
熟悉[服务提供商](guide/providers)。
熟悉[服务提供商](guide/providers)。
For a sample app using the app-wide singleton service that this page describes, see the
<live-example name="ngmodules"></live-example> showcasing all the documented features of NgModules.
@ -141,11 +141,11 @@ a simple object with the following properties:
* `ngModule`: in this example, the `CoreModule` class.
`ngModule` 在这个例子中就是 `CoreModule`
`ngModule` 在这个例子中就是 `CoreModule`
* `providers`: the configured providers.
`providers` - 配置好的服务提供商
`providers` - 配置好的服务提供商
In the <live-example name="ngmodules">live example</live-example>
the root `AppModule` imports the `CoreModule` and adds the
@ -163,7 +163,7 @@ of imported modules.
Import `CoreModule` and use its `forRoot()` method one time, in `AppModule`, because it registers services and you only want to register those services one time in your app. If you were to register them more than once, you could end up with multiple instances of the service and a runtime error.
应该只在 `AppModule` 中导入 `CoreModule` 并只使用一次 `forRoot()` 方法,因为该方法中会注册服务,而你希望那些服务在该应用中只注册一次。
如果你多次注册它们,就可能会得到该服务的多个实例,并导致运行时错误。
如果你多次注册它们,就可能会得到该服务的多个实例,并导致运行时错误。
You can also add a `forRoot()` method in the `CoreModule` that configures
the core `UserService`.
@ -294,11 +294,11 @@ You may also be interested in:
* [Sharing Modules](guide/sharing-ngmodules), which elaborates on the concepts covered on this page.
[共享模块](guide/sharing-ngmodules)解释了本页中涉及的这些概念。
[共享模块](guide/sharing-ngmodules)解释了本页中涉及的这些概念。
* [Lazy Loading Modules](guide/lazy-loading-ngmodules).
[惰性加载模块](guide/lazy-loading-ngmodules)
[惰性加载模块](guide/lazy-loading-ngmodules).
* [NgModule FAQ](guide/ngmodule-faq).

View File

@ -371,7 +371,7 @@ Its intended source is implicit.
Angular sets `let-hero` to the value of the context's `$implicit` property
which `NgFor` has initialized with the hero for the current iteration.
这里并没有指定 `let-hero` 的上下文属性。它的来源是隐式的。
这里并没有指定 `let-hero` 的上下文属性。它的来源是隐式的。
Angular 将 `let-hero` 设置为此上下文中 `$implicit` 属性的值,
它是由 `NgFor` 用当前迭代中的英雄初始化的。

View File

@ -552,7 +552,7 @@ from the _source-to-view_, from _view-to-source_, and in the two-way sequence: _
<td>
One-way<br>from data source<br>to view target
单向<br>从数据源<br>到视图
</td>

View File

@ -1243,6 +1243,38 @@ There is no harm in calling `detectChanges()` more often than is strictly necess
<hr>
{@a dispatch-event}
#### Change an input value with _dispatchEvent()_
#### 使用 `dispatchEvent()` 修改输入值
To simulate user input, you can find the input element and set its `value` property.
要想模拟用户输入,你就要找到 `<input>` 元素并设置它的 `value` 属性。
You will call `fixture.detectChanges()` to trigger Angular's change detection.
But there is an essential, intermediate step.
你要调用 `fixture.detectChanges()` 来触发 Angular 的变更检测。
但那只是一个基本的中间步骤。
Angular doesn't know that you set the input element's `value` property.
It won't read that property until you raise the element's `input` event by calling `dispatchEvent()`.
_Then_ you call `detectChanges()`.
Angular 不知道你设置了这个 `<input>` 元素的 `value` 属性。
在你通过调用 `dispatchEvent()` 触发了该输入框的 `input` 事件之前,它不能读到那个值。
*调用完之后*你再调用 `detectChanges()`
The following example demonstrates the proper sequence.
下面的例子演示了这个调用顺序。
<code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" title="app/hero/hero-detail.component.spec.ts (pipe test)"></code-example>
<hr>
### Component with external files
### 带有外部文件的组件
@ -2672,15 +2704,15 @@ You'll take a different approach with `ActivatedRoute` because
* `paramMap` returns an `Observable` that can emit more than one value
during a test.
在测试期间,`paramMap` 会返回一个能发出多个值的 `Observable`
在测试期间,`paramMap` 会返回一个能发出多个值的 `Observable`
* You need the router helper function, `convertToParamMap()`, to create a `ParamMap`.
你需要路由器的辅助函数 `convertToParamMap()` 来创建 `ParamMap`
你需要路由器的辅助函数 `convertToParamMap()` 来创建 `ParamMap`
* Other _routed components_ tests need a test double for `ActivatedRoute`.
针对*路由目标组件*的其它测试需要一个 `ActivatedRoute` 的测试替身。
针对*路由目标组件*的其它测试需要一个 `ActivatedRoute` 的测试替身。
These differences argue for a re-usable stub class.
@ -3171,23 +3203,23 @@ Tests that exercise the component need ...
* to wait until a hero arrives before elements appear in the DOM.
等获取到英雄之后才能让元素出现在 DOM 中。
等获取到英雄之后才能让元素出现在 DOM 中。
* a reference to the title text.
一个对标题文本的引用。
一个对标题文本的引用。
* a reference to the name input box to inspect and set it.
一个对 name 输入框的引用,以便对它进行探查和修改。
一个对 name 输入框的引用,以便对它进行探查和修改。
* references to the two buttons so they can click them.
引用两个按钮,以便点击它们。
引用两个按钮,以便点击它们。
* spies for some of the component and router methods.
为组件和路由器的方法安插间谍。
为组件和路由器的方法安插间谍。
Even a small form such as this one can produce a mess of tortured conditional setup and CSS element selection.

View File

@ -238,23 +238,23 @@ You will create:
* a server-side app module, `app.server.module.ts`
一个服务端的 app 模块 `app.server.module.ts`
一个服务端的 app 模块 `app.server.module.ts`
* an entry point for the server-side, `main.server.ts`
一个服务端的入口点 `main.server.ts`
一个服务端的入口点 `main.server.ts`
* an express web server to handle requests, `server.ts`
一个用于处理请求的 express Web 服务器
一个用于处理请求的 express Web 服务器
* a TypeScript config file, `tsconfig.server.json`
一个 TypeScript 配置文件 `tsconfig.server.json`
一个 TypeScript 配置文件 `tsconfig.server.json`
* a Webpack config file for the server, `webpack.server.config.js`
一个供服务器使用的 Webpack 配置文件 `webpack.server.config.js`
一个供服务器使用的 Webpack 配置文件 `webpack.server.config.js`
When you're done, the folder structure will look like this:
@ -306,20 +306,20 @@ To get started, install these packages.
在开始之前,要安装下列包。
* `@angular/platform-server` - Universal server-side components.
`@angular/platform-server` - Universal 的服务端元件。
`@angular/platform-server` - Universal 的服务端元件。
* `@nguniversal/module-map-ngfactory-loader` - For handling lazy-loading in the context of a server-render.
`@nguniversal/module-map-ngfactory-loader` - 用于处理服务端渲染环境下的惰性加载。
`@nguniversal/module-map-ngfactory-loader` - 用于处理服务端渲染环境下的惰性加载。
* `@nguniversal/express-engine` - An express engine for Universal applications.
`@nguniversal/express-engine` - Universal 应用的 Express 引擎。
`@nguniversal/express-engine` - Universal 应用的 Express 引擎。
* `ts-loader` - To transpile the server application
`ts-loader` - 用于对服务端应用进行转译。
`ts-loader` - 用于对服务端应用进行转译。
Install them with the following commands:
@ -386,16 +386,16 @@ You can get runtime information about the current platform and the `appId` by in
#### 在 HTTP 中使用绝对地址
The tutorial's `HeroService` and `HeroSearchService` delegate to the Angular `Http` module to fetch application data.
The tutorial's `HeroService` and `HeroSearchService` delegate to the Angular `HttpClient` module to fetch application data.
These services send requests to _relative_ URLs such as `api/heroes`.
教程中的 `HeroService``HeroSearchService` 都委托了 Angular 的 `Http` 模块来获取应用数据。
教程中的 `HeroService``HeroSearchService` 都委托了 Angular 的 `HttpClient` 模块来获取应用数据。
那些服务都把请求发送到了*相对* URL比如 `api/heroes`
In a Universal app, `Http` URLs must be _absolute_ (e.g., `https://my-server.com/api/heroes`)
In a Universal app, HTTP URLs must be _absolute_, for example, `https://my-server.com/api/heroes`
even when the Universal web server is capable of handling those requests.
在 Universal 应用中,`Http` 的 URL 必须是*绝对地址*(比如 `https://my-server.com/api/heroes`
在 Universal 应用中,HTTP 的 URL 必须是*绝对地址*(比如 `https://my-server.com/api/heroes`
只有这样Universal 的 Web 服务器才能处理那些请求。
You'll have to change the services to make requests with absolute URLs when running on the server
@ -410,7 +410,7 @@ inject it into the service, and prepend the origin to the request URL.
Start by changing the `HeroService` constructor to take a second `origin` parameter that is optionally injected via the `APP_BASE_HREF` token.
先为 `HeroService` 的构造函数添加第二个 `origin` 参数,它是可选的,并通过 `APP_BASE_HREF` 令牌进行注入。
先为 `HeroService` 的构造函数添加第二个 `origin` 参数,它是可选的,并通过 `APP_BASE_HREF` 令牌进行注入。
<code-example path="universal/src/app/hero.service.ts" region="ctor" title="src/app/hero.service.ts (constructor with optional origin)">
@ -638,7 +638,7 @@ Express 服务器是一系列中间件构成的管道,它会挨个对 URL 请
You configure the Express server pipeline with calls to `app.get()` like this one for data requests.
你通过通过调用 `app.get()` 来配置 Express 服务器的管道,就像下面这个数据请求一样:
你通过通过调用 `app.get()` 来配置 Express 服务器的管道,就像下面这个数据请求一样:
<code-example path="universal/server.ts" title="server.ts (data URL)" region="data-request" linenums="false">
@ -741,17 +741,17 @@ This config extends from the root's `tsconfig.json` file. Certain settings are n
这个配置扩展了根目录下的 `tsconfig.json` 文件,注意它们在某些设置上的差异。
* The `module` property must be **commonjs** which can be require()'d into our server application.
* The `module` property must be **commonjs** which can be required into our server application.
`module` 属性必须是 **commonjs**,这样它才能被 `require()` 进你的服务端应用。
* The `angularCompilerOptions` section guides the AOT compiler:
`angularCompilerOptions` 部分有一些面向 AOT 编译器的选项:
`angularCompilerOptions` 部分有一些面向 AOT 编译器的选项:
* `entryModule` - the root module of the server application, expressed as `path/to/file#ClassName`.
`entryModule` - 服务端应用的根模块,其格式为 `path/to/file#ClassName`
`entryModule` - 服务端应用的根模块,其格式为 `path/to/file#ClassName`
### Universal Webpack configuration
@ -871,19 +871,19 @@ But clicks, mouse-moves, and keyboard entries are inert.
* Clicking a hero on the Heroes page does nothing.
点击英雄列表页中的英雄没反应。
点击英雄列表页中的英雄没反应。
* You can't add or delete a hero.
你也不能添加或删除英雄。
你也不能添加或删除英雄。
* The search box on the Dashboard page is ignored.
仪表盘页面上的搜索框不理你。
仪表盘页面上的搜索框不理你。
* The _back_ and _save_ buttons on the Details page don't work.
详情页中的 *Back**Save* 按钮也没反应。
详情页中的 *Back**Save* 按钮也没反应。
User events other than `routerLink` clicks aren't supported.
The user must wait for the full client app to arrive.
@ -934,15 +934,15 @@ It also explained some of the key reasons for doing so.
- Facilitate web crawlers (SEO)
帮助网络爬虫SEO
帮助网络爬虫SEO
- Support low-bandwidth or low-power devices
支持低带宽或低功耗设备
支持低带宽或低功耗设备
- Fast first page load
快速加载首屏
快速加载首屏
Angular Universal can greatly improve the perceived startup performance of your app.
The slower the network, the more advantageous it becomes to have Universal display the first page to the user.

View File

@ -423,11 +423,9 @@ Polyfills 最好跟应用代码和 vendor 代码区分开来单独打包。在 `
<div class="callout is-critical">
<header>
<header>Loading polyfills</header>
Loading polyfills
</header>
<header>加载腻子脚本</header>
Load `zone.js` early within `polyfills.ts`, immediately after the other ES6 and metadata shims.

View File

@ -192,11 +192,11 @@ Here are the code files discussed on this page.
* You created the initial application structure using the Angular CLI.
你使用 Angular CLI 创建了初始的应用结构。
你使用 Angular CLI 创建了初始的应用结构。
* You learned that Angular components display data.
你学会了使用 Angular 组件来显示数据。
你学会了使用 Angular 组件来显示数据。
* You used the double curly braces of interpolation to display the app title.

View File

@ -413,27 +413,27 @@ Your app should look like this <live-example></live-example>. Here are the code
* You used the CLI to create a second `HeroesComponent`.
你使用 CLI 创建了第二个组件 `HeroesComponent`
你使用 CLI 创建了第二个组件 `HeroesComponent`
* You displayed the `HeroesComponent` by adding it to the `AppComponent` shell.
你把 `HeroesComponent` 添加到了壳组件 `AppComponent` 中,以便显示它。
你把 `HeroesComponent` 添加到了壳组件 `AppComponent` 中,以便显示它。
* You applied the `UppercasePipe` to format the name.
你使用 `UppercasePipe` 来格式化英雄的名字。
你使用 `UppercasePipe` 来格式化英雄的名字。
* You used two-way data binding with the `ngModel` directive.
你用 `ngModel` 指令实现了双向数据绑定。
你用 `ngModel` 指令实现了双向数据绑定。
* You learned about the `AppModule`.
你知道了 `AppModule`
你知道了 `AppModule`
* You imported the `FormsModule` in the `AppModule` so that Angular would recognize and apply the `ngModel` directive.
你把 `FormsModule` 导入了 `AppModule`,以便 Angular 能识别并应用 `ngModel` 指令。
你把 `FormsModule` 导入了 `AppModule`,以便 Angular 能识别并应用 `ngModel` 指令。
* You learned the importance of declaring components in the `AppModule`
and appreciated that the CLI declared it for you.

View File

@ -69,19 +69,19 @@ Open the `HeroesComponent` template file and make the following changes:
* Add an `<h2>` at the top,
在顶部添加 `<h2>`
在顶部添加 `<h2>`
* Below it add an HTML unordered list (`<ul>`)
然后添加表示无序列表的 HTML 元素(`<ul>`
然后添加表示无序列表的 HTML 元素(`<ul>`
* Insert an `<li>` within the `<ul>` that displays properties of a `hero`.
`<ul>` 中插入一个 `<li>` 元素,以显示单个 `hero` 的属性。
`<ul>` 中插入一个 `<li>` 元素,以显示单个 `hero` 的属性。
* Sprinkle some CSS classes for styling (you'll add the CSS styles shortly).
点缀上一些 CSS 类(稍后你还会添加更多 CSS 样式)。
点缀上一些 CSS 类(稍后你还会添加更多 CSS 样式)。
Make it look like this:
@ -111,15 +111,15 @@ In this example
* `<li>` is the host element
`<li>` 就是 `*ngFor` 的宿主元素
`<li>` 就是 `*ngFor` 的宿主元素
* `heroes` is the list from the `HeroesComponent` class.
`heroes` 就是来自 `HeroesComponent` 类的列表。
`heroes` 就是来自 `HeroesComponent` 类的列表。
* `hero` holds the current hero object for each iteration through the list.
当依次遍历这个列表时,`hero` 会为每个迭代保存当前的英雄对象。
当依次遍历这个列表时,`hero` 会为每个迭代保存当前的英雄对象。
<div class="alert is-important">
@ -414,7 +414,7 @@ The finished `<li>` looks like this:
Your app should look like this <live-example></live-example>.
应用现在变成了这样:<live-example></live-example>
你的应用现在变成了这样:<live-example></live-example>
Here are the code files discussed on this page, including the `HeroesComponent` styles.
@ -439,19 +439,19 @@ Here are the code files discussed on this page, including the `HeroesComponent`
* The Tour of Heroes app displays a list of heroes in a Master/Detail view.
英雄指南应用在一个主从视图中显示了英雄列表。
英雄指南应用在一个主从视图中显示了英雄列表。
* The user can select a hero and see that hero's details.
用户可以选择一个英雄,并查看该英雄的详情。
用户可以选择一个英雄,并查看该英雄的详情。
* You used `*ngFor` to display a list.
你使用 `*ngFor` 显示了一个列表。
你使用 `*ngFor` 显示了一个列表。
* You used `*ngIf` to conditionally include or exclude a block of HTML.
你使用 `*ngIf` 来根据条件包含或排除了一段 HTML。
你使用 `*ngIf` 来根据条件包含或排除了一段 HTML。
* You can toggle a CSS style class with a `class` binding.

View File

@ -247,11 +247,11 @@ Here are the code files discussed on this page and your app should look like thi
* You created a separate, reusable `HeroDetailComponent`.
你创建了一个独立的、可复用的 `HeroDetailComponent` 组件。
你创建了一个独立的、可复用的 `HeroDetailComponent` 组件。
* You used a [property binding](guide/template-syntax#property-binding) to give the parent `HeroesComponent` control over the child `HeroDetailComponent`.
你用[属性绑定](guide/template-syntax#property-binding)语法来让父组件 `HeroesComponent` 可以控制子组件 `HeroDetailComponent`
你用[属性绑定](guide/template-syntax#property-binding)语法来让父组件 `HeroesComponent` 可以控制子组件 `HeroDetailComponent`
* You used the [`@Input` decorator](guide/template-syntax#inputs-outputs)
to make the `hero` property available for binding

View File

@ -455,19 +455,19 @@ In this section you will
* add a `MessagesComponent` that displays app messages at the bottom of the screen.
添加一个 `MessagesComponent`,它在屏幕的底部显示应用中的消息。
添加一个 `MessagesComponent`,它在屏幕的底部显示应用中的消息。
* create an injectable, app-wide `MessageService` for sending messages to be displayed
创建一个可注入的、全应用级别的 `MessageService`,用于发送要显示的消息。
创建一个可注入的、全应用级别的 `MessageService`,用于发送要显示的消息。
* inject `MessageService` into the `HeroService`
`MessageService` 注入到 `HeroService` 中。
`MessageService` 注入到 `HeroService` 中。
* display a message when `HeroService` fetches heroes successfully.
`HeroService` 成功获取了英雄数据时显示一条消息。
`HeroService` 成功获取了英雄数据时显示一条消息。
### Create _MessagesComponent_
@ -645,16 +645,16 @@ This template binds directly to the component's `messageService`.
* The `*ngIf` only displays the messages area if there are messages to show.
`*ngIf` 只有当在有消息时才会显示消息区。
`*ngIf` 只有当在有消息时才会显示消息区。
* An `*ngFor` presents the list of messages in repeated `<div>` elements.
`*ngFor` 用来在一系列 `<div>` 元素中展示消息列表。
`*ngFor` 用来在一系列 `<div>` 元素中展示消息列表。
* An Angular [event binding](guide/template-syntax#event-binding) binds the button's click event
to `MessageService.clear()`.
Angular 的[事件绑定](guide/template-syntax#event-binding)把按钮的 `click` 事件绑定到了 `MessageService.clear()`
Angular 的[事件绑定](guide/template-syntax#event-binding)把按钮的 `click` 事件绑定到了 `MessageService.clear()`
The messages will look better when you add the private CSS styles to `messages.component.css`
as listed in one of the ["final code review"](#final-code-review) tabs below.
@ -721,35 +721,35 @@ Here are the code files discussed on this page and your app should look like thi
* You refactored data access to the `HeroService` class.
你把数据访问逻辑重构到了 `HeroService` 类中。
你把数据访问逻辑重构到了 `HeroService` 类中。
* You _provided_ the `HeroService` in the root `AppModule` so that it can be injected anywhere.
你在根模块 `AppModule` 中提供了 `HeroService` 服务,以便在别处可以注入它。
你在根模块 `AppModule` 中提供了 `HeroService` 服务,以便在别处可以注入它。
* You used [Angular Dependency Injection](guide/dependency-injection) to inject it into a component.
你使用 [Angular 依赖注入](guide/dependency-injection)机制把它注入到了组件中。
你使用 [Angular 依赖注入](guide/dependency-injection)机制把它注入到了组件中。
* You gave the `HeroService` _get data_ method an asynchronous signature.
你给 `HeroService` 中获取数据的方法提供了一个异步的函数签名。
你给 `HeroService` 中获取数据的方法提供了一个异步的函数签名。
* You discovered `Observable` and the RxJS _Observable_ library.
你发现了 `Observable` 以及 RxJS 库。
你发现了 `Observable` 以及 RxJS 库。
* You used RxJS `of()` to return an _Observable_ of mock heroes (`Observable<Hero[]>`).
你使用 RxJS 的 `of()` 方法返回了一个模拟英雄数据的*可观察对象* (`Observable<Hero[]>`)。
你使用 RxJS 的 `of()` 方法返回了一个模拟英雄数据的*可观察对象* (`Observable<Hero[]>`)。
* The component's `ngOnInit` lifecycle hook calls the `HeroService` method, not the constructor.
在组件的 `ngOnInit` 生命周期钩子中调用 `HeroService` 方法,而不是构造函数中。
在组件的 `ngOnInit` 生命周期钩子中调用 `HeroService` 方法,而不是构造函数中。
* You created a `MessageService` for loosely-coupled communication between classes.
你创建了一个 `MessageService`,以便在类之间实现松耦合通讯。
你创建了一个 `MessageService`,以便在类之间实现松耦合通讯。
* The `HeroService` injected into a component is created with another injected service,
`MessageService`.

View File

@ -32,9 +32,9 @@ When youre done, users will be able to navigate the app like this:
</figure>
## Add the _AppRoutingModule_
## Add the `AppRoutingModule`
## 添加 _AppRoutingModule_
## 添加 `AppRoutingModule`
An Angular best practice is to load and configure the router in a separate, top-level module
that is dedicated to routing and imported by the root `AppModule`.
@ -235,9 +235,9 @@ You should see the familiar heroes master/detail view.
{@a routerlink}
## Add a navigation link (_routerLink_)
## Add a navigation link (`routerLink`)
## 添加路由链接 (*routerLink*)
## 添加路由链接 (`routerLink`)
Users shouldn't have to paste a route URL into the address bar.
They should be able to click a link to navigate.
@ -336,15 +336,15 @@ The _template_ presents a grid of hero name links.
* The `*ngFor` repeater creates as many links as are in the component's `heroes` array.
`*ngFor` 复写器为组件的 `heroes` 数组中的每个条目创建了一个链接。
`*ngFor` 复写器为组件的 `heroes` 数组中的每个条目创建了一个链接。
* The links are styled as colored blocks by the `dashboard.component.css`.
这些链接被 `dashboard.component.css` 中的样式格式化成了一些色块。
这些链接被 `dashboard.component.css` 中的样式格式化成了一些色块。
* The links don't go anywhere yet but [they will shortly](#hero-details).
这些链接还没有指向任何地方,但[很快就会了](#hero-details)。
这些链接还没有指向任何地方,但[很快就会了](#hero-details)。
The _class_ is similar to the `HeroesComponent` class.
@ -352,15 +352,15 @@ The _class_ is similar to the `HeroesComponent` class.
* It defines a `heroes` array property.
它定义了一个 `heroes` 数组属性。
它定义了一个 `heroes` 数组属性。
* The constructor expects Angular to inject the `HeroService` into a private `heroService` property.
它的构造函数希望 Angular 把 `HeroService` 注入到私有的 `heroService` 属性中。
它的构造函数希望 Angular 把 `HeroService` 注入到私有的 `heroService` 属性中。
* The `ngOnInit()` lifecycle hook calls `getHeroes`.
`ngOnInit()` 生命周期钩子中调用 `getHeroes`
`ngOnInit()` 生命周期钩子中调用 `getHeroes`
This `getHeroes` reduces the number of heroes displayed to four
(2nd, 3rd, 4th, and 5th).
@ -485,7 +485,7 @@ and liberate it from the `HeroesComponent`.
在这一节,你将能导航到 `HeroDetailComponent`,并把它从 `HeroesComponent` 中解放出来。
### Delete _hero details_ from _HeroesComponent_
### Delete _hero details_ from `HeroesComponent`
### 从 `HeroesComponent` 中删除*英雄详情*
@ -551,7 +551,7 @@ At this point, all application routes are in place.
</code-example>
### _DashboardComponent_ hero links
### `DashboardComponent` hero links
### `DashboardComponent` 中的英雄链接
@ -580,7 +580,7 @@ to insert the current interation's `hero.id` into each
{@a heroes-component-links}
### _HeroesComponent_ hero links
### `HeroesComponent` hero links
### `HeroesComponent` 中的英雄链接
@ -661,15 +661,15 @@ The `HeroDetailComponent` needs a new way to obtain the _hero-to-display_.
* Get the route that created it,
获取创建本组件的路由,
获取创建本组件的路由,
* Extract the `id` from the route
从这个路由中提取出 `id`
从这个路由中提取出 `id`
* Acquire the hero with that `id` from the server via the `HeroService`
通过 `HeroService` 从服务器上获取具有这个 `id` 的英雄数据。
通过 `HeroService` 从服务器上获取具有这个 `id` 的英雄数据。
Add the following imports:
@ -752,9 +752,9 @@ Add it now.
刷新浏览器,应用挂了。出现一个编译错误,因为 `HeroService` 没有一个名叫 `getHero()` 的方法。
这就添加它。
### Add *HeroService.getHero()*
### Add `HeroService.getHero()`
### 添加 *HeroService.getHero()*
### 添加 `HeroService.getHero()`
Open `HeroService` and add this `getHero()` method
@ -865,9 +865,9 @@ Here are the code files discussed on this page and your app should look like thi
{@a appmodule}
#### _AppRoutingModule_ and _AppModule_
#### _AppRoutingModule_, _AppModule_, and _HeroService_
#### _AppRoutingModule_ 与 _AppModule_
#### `AppRoutingModule``AppModule``HeroService`
<code-tabs>
@ -879,6 +879,10 @@ Here are the code files discussed on this page and your app should look like thi
title="src/app/app.module.ts"
path="toh-pt5/src/app/app.module.ts">
</code-pane>
<code-pane
title="src/app/hero.service.ts"
path="toh-pt5/src/app/hero.service.ts">
</code-pane>
</code-tabs>
@ -968,31 +972,31 @@ Here are the code files discussed on this page and your app should look like thi
* You added the Angular router to navigate among different components.
添加了 Angular *路由器*在各个不同组件之间导航。
添加了 Angular *路由器*在各个不同组件之间导航。
* You turned the `AppComponent` into a navigation shell with `<a>` links and a `<router-outlet>`.
你使用一些 `<a>` 链接和一个 `<router-outlet>``AppComponent` 转换成了一个导航用的壳组件。
你使用一些 `<a>` 链接和一个 `<router-outlet>``AppComponent` 转换成了一个导航用的壳组件。
* You configured the router in an `AppRoutingModule`
你在 `AppRoutingModule` 中配置了路由器。
你在 `AppRoutingModule` 中配置了路由器。
* You defined simple routes, a redirect route, and a parameterized route.
你定义了一些简单路由、一个重定向路由和一个参数化路由。
你定义了一些简单路由、一个重定向路由和一个参数化路由。
* You used the `routerLink` directive in anchor elements.
你在 `<a>` 元素中使用了 `routerLink` 指令。
你在 `<a>` 元素中使用了 `routerLink` 指令。
* You refactored a tightly-coupled master/detail view into a routed detail view.
你把一个紧耦合的主从视图重构成了带路由的详情视图。
你把一个紧耦合的主从视图重构成了带路由的详情视图。
* You used router link parameters to navigate to the detail view of a user-selected hero.
你使用路由链接参数来导航到所选英雄的详情视图。
你使用路由链接参数来导航到所选英雄的详情视图。
* You shared the `HeroService` among multiple components.

View File

@ -7,15 +7,15 @@ Angular's `HttpClient`.
* The `HeroService` gets hero data with HTTP requests.
`HeroService` 通过 HTTP 请求获取英雄数据。
`HeroService` 通过 HTTP 请求获取英雄数据。
* Users can add, edit, and delete heroes and save these changes over HTTP.
用户可以添加、编辑和删除英雄,并通过 HTTP 来保存这些更改。
用户可以添加、编辑和删除英雄,并通过 HTTP 来保存这些更改。
* Users can search for heroes by name.
用户可以根据名字搜索英雄。
用户可以根据名字搜索英雄。
When you're done with this page, the app should look like this <live-example></live-example>.
@ -35,15 +35,15 @@ To make `HttpClient` available everywhere in the app,
* open the root `AppModule`,
打开根模块 `AppModule`
打开根模块 `AppModule`
* import the `HttpClientModule` symbol from `@angular/common/http`,
`@angular/common/http` 中导入 `HttpClientModule` 符号,
`@angular/common/http` 中导入 `HttpClientModule` 符号,
* add it to the `@NgModule.imports` array.
把它加入 `@NgModule.imports` 数组。
把它加入 `@NgModule.imports` 数组。
## Simulate a data server
@ -403,16 +403,16 @@ There are three significant differences from `getHeroes()`.
* it constructs a request URL with the desired hero's id.
它使用想获取的英雄的 id 构建了一个请求 URL。
它使用想获取的英雄的 id 构建了一个请求 URL。
* the server should respond with a single hero rather than an array of heroes.
服务器应该使用单个英雄作为回应,而不是一个英雄数组。
服务器应该使用单个英雄作为回应,而不是一个英雄数组。
* therefore, `getHero` returns an `Observable<Hero>` ("_an observable of Hero objects_")
rather than an observable of hero _arrays_ .
所以,`getHero` 会返回 `Observable<Hero>`(“一个可观察的*单个英雄对象*”),而不是一个可观察的英雄对象*数组*。
所以,`getHero` 会返回 `Observable<Hero>`(“一个可观察的*单个英雄对象*”),而不是一个可观察的英雄对象*数组*。
## Update heroes
@ -468,15 +468,15 @@ The `HttpClient.put()` method takes three parameters
* the URL
URL 地址
URL 地址
* the data to update (the modified hero in this case)
要修改的数据(这里就是修改后的英雄)
要修改的数据(这里就是修改后的英雄)
* options
选项
选项
The URL is unchanged. The heroes web API knows which hero to update by looking at the hero's `id`.
@ -554,12 +554,12 @@ Add the following `addHero()` method to the `HeroService` class.
* it calls `HttpClient.post()` instead of `put()`.
它调用 `HttpClient.post()` 而不是 `put()`
它调用 `HttpClient.post()` 而不是 `put()`
* it expects the server to generates an id for the new hero,
which it returns in the `Observable<Hero>` to the caller.
它期待服务器为这个新的英雄生成一个 id然后把它通过 `Observable<Hero>` 返回给调用者。
它期待服务器为这个新的英雄生成一个 id然后把它通过 `Observable<Hero>` 返回给调用者。
Refresh the browser and add some heroes.
@ -643,19 +643,19 @@ Note that
* it calls `HttpClient.delete`.
它调用了 `HttpClient.delete`
它调用了 `HttpClient.delete`
* the URL is the heroes resource URL plus the `id` of the hero to delete
URL 就是英雄的资源 URL 加上要删除的英雄的 `id`
URL 就是英雄的资源 URL 加上要删除的英雄的 `id`
* you don't send data as you did with `put` and `post`.
你不用像 `put``post` 中那样发送任何数据。
你不用像 `put``post` 中那样发送任何数据。
* you still send the `httpOptions`.
你仍要发送 `httpOptions`
你仍要发送 `httpOptions`
Refresh the browser and try the new delete functionality.
@ -882,17 +882,17 @@ Here's the code.
* `debounceTime(300)` waits until the flow of new string events pauses for 300 milliseconds
before passing along the latest string. You'll never make requests more frequently than 300ms.
在传出最终字符串之前,`debounceTime(300)` 将会等待,直到新增字符串的事件暂停了 300 毫秒。
在传出最终字符串之前,`debounceTime(300)` 将会等待,直到新增字符串的事件暂停了 300 毫秒。
你实际发起请求的间隔永远不会小于 300ms。
* `distinctUntilChanged` ensures that a request is sent only if the filter text changed.
`distinctUntilChanged` 会确保只在过滤条件变化时才发送请求。
`distinctUntilChanged` 会确保只在过滤条件变化时才发送请求。
* `switchMap()` calls the search service for each search term that makes it through `debounce` and `distinctUntilChanged`.
It cancels and discards previous search observables, returning only the latest search service observable.
`switchMap()` 会为每个从 `debounce``distinctUntilChanged` 中通过的搜索词调用搜索服务。
`switchMap()` 会为每个从 `debounce``distinctUntilChanged` 中通过的搜索词调用搜索服务。
它会取消并丢弃以前的搜索可观察对象,只保留最近的。
<div class="l-sub-section">
@ -1045,27 +1045,27 @@ You're at the end of your journey, and you've accomplished a lot.
* You added the necessary dependencies to use HTTP in the app.
你添加了在应用程序中使用 HTTP 的必备依赖。
你添加了在应用程序中使用 HTTP 的必备依赖。
* You refactored `HeroService` to load heroes from a web API.
你重构了 `HeroService`,以通过 web API 来加载英雄数据。
你重构了 `HeroService`,以通过 web API 来加载英雄数据。
* You extended `HeroService` to support `post()`, `put()`, and `delete()` methods.
你扩展了 `HeroService` 来支持 `post()``put()``delete()` 方法。
你扩展了 `HeroService` 来支持 `post()``put()``delete()` 方法。
* You updated the components to allow adding, editing, and deleting of heroes.
你修改了组件,以允许用户添加、编辑和删除英雄。
你修改了组件,以允许用户添加、编辑和删除英雄。
* You configured an in-memory web API.
你配置了一个内存 Web API。
你配置了一个内存 Web API。
* You learned how to use Observables.
你学会了如何使用“可观察对象”。
你学会了如何使用“可观察对象”。
This concludes the "Tour of Heroes" tutorial.
You're ready to learn more about Angular development in the fundamentals section,

View File

@ -15911,7 +15911,7 @@
},
{
"original": "Routed",
"translation": "路由",
"translation": "路由",
"sourceFile": "/Users/twer/private/GDE/angular-cn/aio/content/guide/module-types.md"
},
{
@ -17641,7 +17641,7 @@
},
{
"original": "You may also be interested in the following:",
"translation": "你可能还对下列内容感兴趣:",
"translation": "你可能还对下列内容感兴趣:",
"sourceFile": "/Users/twer/private/GDE/angular-cn/aio/content/guide/ngmodules.md"
},
{
@ -19269,11 +19269,6 @@
"translation": "文件",
"sourceFile": "/Users/twer/private/GDE/angular-cn/aio/content/guide/quickstart.md"
},
{
"original": "Purpose",
"translation": "目的",
"sourceFile": "/Users/twer/private/GDE/angular-cn/aio/content/guide/quickstart.md"
},
{
"original": "Inside `e2e/` live the end-to-end tests.\n They shouldn't be inside `src/` because e2e tests are really a separate app that\n just so happens to test your main app.\n That's also why they have their own `tsconfig.e2e.json`.",
"translation": "在 `e2e/` 下是端到端end-to-end测试。\n 它们不在 `src/` 下,是因为端到端测试实际上和应用是相互独立的,它只适用于测试你的应用而已。\n 这也就是为什么它会拥有自己的 `tsconfig.json`。",
@ -43694,4 +43689,4 @@
"translation": "《英雄指南》教程结束了。\n如果你准备开始学习 Angular 开发的原理,请开始 [架构](guide/architecture \"Architecture\") 一章。",
"sourceFile": "/Users/twer/private/GDE/angular-cn/aio/content/tutorial/toh-pt6.md"
}
]
]