fix: 把提供商批量替换为提供者

This commit is contained in:
Zhicheng WANG 2020-04-15 10:19:34 +08:00
parent c1800730ed
commit 7a49faba2d
42 changed files with 328 additions and 328 deletions

View File

@ -110,7 +110,7 @@ export class MyComponent {}
The compiler generates the component factory, which includes the `useValue` provider code, in a separate module. _That_ factory module can't reach back to _this_ source module to access the local (non-exported) `foo` variable.
编译器会在单独的模块中生成这个 `userValue` 提供的代码。*那个*工厂模块不能访问*这个*源码模块,无法访问这个(未导出的)`foo` 变量。
编译器会在单独的模块中生成这个 `userValue` 提供的代码。*那个*工厂模块不能访问*这个*源码模块,无法访问这个(未导出的)`foo` 变量。
You could fix the problem by initializing `foo`.
@ -124,7 +124,7 @@ let foo = 42; // initialized
The compiler will [fold](guide/aot-compiler#code-folding) the expression into the provider as if you had written this.
编译器会将表达式[折叠](guide/aot-compiler#code-folding)到提供中,就像你自己写的一样。
编译器会将表达式[折叠](guide/aot-compiler#code-folding)到提供中,就像你自己写的一样。
```ts
@ -346,7 +346,7 @@ export abstract class MyStrategy { }
For example, you may have set a providers `useFactory` property to a locally defined function that you neglected to export.
比如,你可能已经把某个服务提供`useFactory` 属性设置成了一个局部定义但忘了导出的函数。
比如,你可能已经把某个服务提供`useFactory` 属性设置成了一个局部定义但忘了导出的函数。
```ts
@ -401,7 +401,7 @@ _Function calls are not supported. Consider replacing the function or lambda wit
The compiler does not currently support [function expressions or lambda functions](guide/aot-compiler#function-expression).
For example, you cannot set a provider's `useFactory` to an anonymous function or arrow function like this.
编译器当前不支持[函数表达式或 lambda 函数](guide/aot-compiler#function-expression) 。例如,您不能将提供`useFactory` 设置为这样的匿名函数或箭头函数。
编译器当前不支持[函数表达式或 lambda 函数](guide/aot-compiler#function-expression) 。例如,您不能将提供`useFactory` 设置为这样的匿名函数或箭头函数。
```ts
@ -418,7 +418,7 @@ For example, you cannot set a provider's `useFactory` to an anonymous function o
You also get this error if you call a function or method in a provider's `useValue`.
如果你在某个提供`useValue` 中调用函数或方法,也会导致这个错误。
如果你在某个提供`useValue` 中调用函数或方法,也会导致这个错误。
```ts
@ -435,7 +435,7 @@ import { calculateValue } from './utilities';
To correct this error, export a function from the module and refer to the function in a `useFactory` provider instead.
要改正这个问题,就要从模块中导出这个函数,并改成在服务提供`useFactory` 中引用该函数。
要改正这个问题,就要从模块中导出这个函数,并改成在服务提供`useFactory` 中引用该函数。
```ts
@ -582,7 +582,7 @@ you can finesse the problem in four steps:
1. Add a `useFactory` provider with that factory function.
使用该工厂函数添加一个 `useFactory` 提供
使用该工厂函数添加一个 `useFactory` 提供
1. Use `@Inject` to inject the instance.

View File

@ -87,7 +87,7 @@ Angular inserts an instance of the `HeroListComponent` view between those tags.
* `providers`: An array of [providers](guide/glossary#provider) for services that the component requires. In the example, this tells Angular how to provide the `HeroService` instance that the component's constructor uses to get the list of heroes to display.
`providers`:当前组件所需的服务[提供](guide/glossary#provider)的一个数组。在这个例子中,它告诉 Angular 该如何提供一个 `HeroService` 实例,以获取要显示的英雄列表。
`providers`:当前组件所需的服务[提供](guide/glossary#provider)的一个数组。在这个例子中,它告诉 Angular 该如何提供一个 `HeroService` 实例,以获取要显示的英雄列表。
## Templates and views

View File

@ -7,7 +7,7 @@ NgModules are containers for a cohesive block of code dedicated to an applicatio
Angular 应用是模块化的,它拥有自己的模块化系统,称作 *NgModule*
一个 NgModule 就是一个容器,用于存放一些内聚的代码块,这些代码块专注于某个应用领域、某个工作流或一组紧密相关的功能。
它可以包含一些组件、服务提供或其它代码文件,其作用域由包含它们的 NgModule 定义。
它可以包含一些组件、服务提供或其它代码文件,其作用域由包含它们的 NgModule 定义。
它还可以导入一些由其它模块中导出的功能,并导出一些指定的功能供其它 NgModule 使用。
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.
@ -41,7 +41,7 @@ NgModule 是一个带有 `@NgModule()` 装饰器的类。`@NgModule()` 装饰器
* `providers`: 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.)
`providers` —— 本模块向全局服务中贡献的那些[服务](guide/architecture-services)的创建器。
这些服务能被本应用中的任何部分使用。(你也可以在组件级别指定服务提供,这通常是首选方式。)
这些服务能被本应用中的任何部分使用。(你也可以在组件级别指定服务提供,这通常是首选方式。)
* `bootstrap`: The main application view, called the *root component*, which hosts all other app views. Only the *root NgModule* should set the `bootstrap` property.

View File

@ -31,7 +31,7 @@ You can also make your app more adaptable by injecting different providers of th
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
@ -83,14 +83,14 @@ Similarly, use the `@Injectable()` decorator to indicate that a component or oth
* A *provider* is an object that tells an injector how to obtain or create a dependency.
*提供*是一个对象,用来告诉注入器应该如何获取或创建依赖。
*提供*是一个对象,用来告诉注入器应该如何获取或创建依赖。
For any dependency that you need in your app, you must register a provider with the app's injector,
so that the injector can use the provider to create new instances.
For a service, the provider is typically the service class itself.
你的应用中所需的任何依赖,都必须使用该应用的注入器来注册一个提供商,以便注入器可以使用这个提供商来创建新实例。
对于服务,该提供通常就是服务类本身。
你的应用中所需的任何依赖,都必须使用该应用的注入器来注册一个提供者,以便注入器可以使用这个提供者来创建新实例。
对于服务,该提供通常就是服务类本身。
<div class="alert is-helpful">
@ -109,7 +109,7 @@ When Angular creates a new instance of a component class, it determines which se
When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.
当 Angular 发现某个组件依赖某个服务时,它会首先检查是否该注入器中已经有了那个服务的任何现有实例。如果所请求的服务尚不存在,注入器就会使用以前注册的服务提供来制作一个,并把它加入注入器中,然后把该服务返回给 Angular。
当 Angular 发现某个组件依赖某个服务时,它会首先检查是否该注入器中已经有了那个服务的任何现有实例。如果所请求的服务尚不存在,注入器就会使用以前注册的服务提供来制作一个,并把它加入注入器中,然后把该服务返回给 Angular。
When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.
@ -133,11 +133,11 @@ or you can register providers with specific modules or components.
You register providers in the metadata of the service (in the `@Injectable()` decorator),
or in the `@NgModule()` or `@Component()` metadata
对于要用到的任何服务,你必须至少注册一个*提供商*。服务可以在自己的元数据中把自己注册为提供商,这样可以让自己随处可用。或者,你也可以为特定的模块或组件注册提供商。要注册提供商,就要在服务的 `@Injectable()` 装饰器中提供它的元数据,或者在`@NgModule()` 或 `@Component()` 的元数据中。
对于要用到的任何服务,你必须至少注册一个*提供者*。服务可以在自己的元数据中把自己注册为提供者,这样可以让自己随处可用。或者,你也可以为特定的模块或组件注册提供者。要注册提供者,就要在服务的 `@Injectable()` 装饰器中提供它的元数据,或者在`@NgModule()` 或 `@Component()` 的元数据中。
* By default, the Angular CLI command [`ng generate service`](cli/generate) registers a provider with the root injector for your service by including provider metadata in the `@Injectable()` decorator. The tutorial uses this method to register the provider of HeroService class definition.
默认情况下Angular CLI 的 [`ng generate service`](cli/generate) 命令会在 `@Injectable()` 装饰器中提供元数据来把它注册到根注入器中。本教程就用这种方法注册了 HeroService 的提供
默认情况下Angular CLI 的 [`ng generate service`](cli/generate) 命令会在 `@Injectable()` 装饰器中提供元数据来把它注册到根注入器中。本教程就用这种方法注册了 HeroService 的提供
```
@Injectable({
@ -150,11 +150,11 @@ or in the `@NgModule()` or `@Component()` metadata
Registering the provider in the `@Injectable()` metadata also allows Angular to optimize an app
by removing the service from the compiled app if it isn't used.
当你在根一级提供服务时Angular 会为 HeroService 创建一个单一的共享实例,并且把它注入到任何想要它的类中。这种在 `@Injectable` 元数据中注册提供的方式还让 Angular 能够通过移除那些从未被用过的服务来优化大小。
当你在根一级提供服务时Angular 会为 HeroService 创建一个单一的共享实例,并且把它注入到任何想要它的类中。这种在 `@Injectable` 元数据中注册提供的方式还让 Angular 能够通过移除那些从未被用过的服务来优化大小。
* When you register a provider with a [specific NgModule](guide/architecture-modules), the same instance of a service is available to all components in that NgModule. To register at this level, use the `providers` property of the `@NgModule()` decorator,
当你使用[特定的 NgModule](guide/architecture-modules) 注册提供时,该服务的同一个实例将会对该 NgModule 中的所有组件可用。要想在这一层注册,请用 `@NgModule()` 装饰器中的 `providers` 属性:
当你使用[特定的 NgModule](guide/architecture-modules) 注册提供时,该服务的同一个实例将会对该 NgModule 中的所有组件可用。要想在这一层注册,请用 `@NgModule()` 装饰器中的 `providers` 属性:
```
@NgModule({
@ -170,8 +170,8 @@ or in the `@NgModule()` or `@Component()` metadata
service with each new instance of that component.
At the component level, register a service provider in the `providers` property of the `@Component()` metadata.
当你在组件级注册提供时,你会为该组件的每一个新实例提供该服务的一个新实例。
要在组件级注册,就要在 `@Component()` 元数据的 `providers` 属性中注册服务提供
当你在组件级注册提供时,你会为该组件的每一个新实例提供该服务的一个新实例。
要在组件级注册,就要在 `@Component()` 元数据的 `providers` 属性中注册服务提供
<code-example path="architecture/src/app/hero-list.component.ts" header="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>

View File

@ -23,7 +23,7 @@ NgModule 会把相关的代码收集到一些功能集中。Angular 应用就是
* 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.
组件使用*服务*。服务会提供那些与视图不直接相关的功能。服务提供可以作为*依赖*被*注入*到组件中,
组件使用*服务*。服务会提供那些与视图不直接相关的功能。服务提供可以作为*依赖*被*注入*到组件中,
这能让你的代码更加模块化、更加可复用、更加高效。
Both components and services are simply classes, with *decorators* that mark their type and provide metadata that tells Angular how to use them.

View File

@ -77,7 +77,7 @@ The `@NgModule` decorator identifies `AppModule` as an `NgModule` class.
* **_providers_**&mdash;the service providers.
**_providers_** —— 各种服务提供
**_providers_** —— 各种服务提供
* **_bootstrap_**&mdash;the _root_ component that Angular creates and inserts
into the `index.html` host web page.
@ -235,7 +235,7 @@ them when using feature modules and lazy loading. For more information, see
[Providers](guide/providers).
`providers` 数组中列出了该应用所需的服务。当直接把服务列在这里时,它们是全应用范围的。
当你使用特性模块和惰性加载时,它们是范围化的。要了解更多,参见[服务提供](guide/providers)。
当你使用特性模块和惰性加载时,它们是范围化的。要了解更多,参见[服务提供](guide/providers)。
## The `bootstrap` array

View File

@ -55,7 +55,7 @@
<p>Defines a module that contains components, directives, pipes, and providers.</p>
<p>定义一个模块,其中可以包含组件、指令、管道和服务提供</p>
<p>定义一个模块,其中可以包含组件、指令、管道和服务提供</p>
</td>
@ -120,7 +120,7 @@ is available to <code>declarations</code> of this module.</p>
<p>List of dependency injection providers visible both to the contents of this module and to importers of this module.</p>
<p>依赖注入提供的列表,本模块以及本模块导入的所有模块中的内容都可以看见它们。</p>
<p>依赖注入提供的列表,本模块以及本模块导入的所有模块中的内容都可以看见它们。</p>
</td>
@ -617,7 +617,7 @@ is available to <code>declarations</code> of this module.</p>
<p>Declares that a class can be provided and injected by other classes. Without this decorator, the compiler won't generate enough metadata to allow the class to be created properly when it's injected somewhere.</p>
<p>声明某个类可以注册为提供,并能被另一个类注入。如果没有该装饰器,编译器就不会生成足够的元数据,当它被注入到别处时,就无法正常创建该类。</p>
<p>声明某个类可以注册为提供,并能被另一个类注入。如果没有该装饰器,编译器就不会生成足够的元数据,当它被注入到别处时,就无法正常创建该类。</p>
</td>
</tr>
@ -675,7 +675,7 @@ is available to <code>declarations</code> of this module.</p>
<p>List of dependency injection providers for this directive and its children.</p>
<p>该指令及其子指令的依赖注入提供列表。</p>
<p>该指令及其子指令的依赖注入提供列表。</p>
</td>
@ -733,7 +733,7 @@ so the <code>@Directive</code> configuration applies to components as well</p>
<p>List of dependency injection providers scoped to this component's view.</p>
<p>依赖注入提供列表,但它们的范围被限定为当前组件的视图。</p>
<p>依赖注入提供列表,但它们的范围被限定为当前组件的视图。</p>
</td>
@ -1119,7 +1119,7 @@ so the <code>@Directive</code> configuration applies to components as well</p>
<p>Sets or overrides the provider for <code>MyService</code> to the <code>MyMockService</code> class.</p>
<p><code>MyService</code> 的服务提供设置或改写为 <code>MyMockService</code> 类。</p>
<p><code>MyService</code> 的服务提供设置或改写为 <code>MyMockService</code> 类。</p>
</td>
@ -1135,7 +1135,7 @@ so the <code>@Directive</code> configuration applies to components as well</p>
<p>Sets or overrides the provider for <code>MyService</code> to the <code>myFactory</code> factory function.</p>
<p><code>MyService</code> 的服务提供设置或改写为 <code>myFactory</code> 工厂函数。</p>
<p><code>MyService</code> 的服务提供设置或改写为 <code>myFactory</code> 工厂函数。</p>
</td>
@ -1151,7 +1151,7 @@ so the <code>@Directive</code> configuration applies to components as well</p>
<p>Sets or overrides the provider for <code>MyValue</code> to the value <code>41</code>.</p>
<p><code>MyValue</code> 的服务提供改写为一个特定的值 <code>41</code></p>
<p><code>MyValue</code> 的服务提供改写为一个特定的值 <code>41</code></p>
</td>

View File

@ -70,7 +70,7 @@ This builder, among other things, ensures that the library is always built with
To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality (such as NgModules, service providers and general utility functions) through a single import path.
要让库代码可以复用,你必须为它定义一个公共的 API。这个“用户层”定义了库中消费者的可用内容。该库的用户应该可以通过单个的导入路径来访问公共功能如NgModules、服务提供和工具函数)。
要让库代码可以复用,你必须为它定义一个公共的 API。这个“用户层”定义了库中消费者的可用内容。该库的用户应该可以通过单个的导入路径来访问公共功能如NgModules、服务提供和工具函数)。
The public API for your library is maintained in the `public-api.ts` file in your library folder.
Anything exported from this file is made public when your library is imported into an application.
@ -105,11 +105,11 @@ Here are some things to consider in migrating application functionality to a lib
* Services should declare their own providers (rather than declaring providers in the NgModule or a component), so that they are *tree-shakable*. This allows the compiler to leave the service out of the bundle if it never gets injected into the application that imports the library. For more about this, see [Tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers).
服务应该声明自己的提供商(而不是在 NgModule 或组件中声明提供商),这样它们才是*可摇树优化的* 。这样,如果该服务从未被注入到导入该库的应用中,编译器就会把该服务从发布包中删除。欲知详情,请参阅[可摇树优化的提供](guide/dependency-injection-providers#tree-shakable-providers) 。
服务应该声明自己的提供者(而不是在 NgModule 或组件中声明提供者),这样它们才是*可摇树优化的* 。这样,如果该服务从未被注入到导入该库的应用中,编译器就会把该服务从发布包中删除。欲知详情,请参阅[可摇树优化的提供](guide/dependency-injection-providers#tree-shakable-providers) 。
* If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` patterns](guide/singleton-services) provided by the [RouterModule](api/router/RouterModule).
如果你在多个 NgModule 中注册全局服务提供商或共享提供商,请使用 [RouterModule](api/router/RouterModule) 提供的 [`forRoot()` 和 `forChild()` 模式](guide/singleton-services) 。
如果你在多个 NgModule 中注册全局服务提供者或共享提供者,请使用 [RouterModule](api/router/RouterModule) 提供的 [`forRoot()` 和 `forChild()` 模式](guide/singleton-services) 。
* Check all internal dependencies.

View File

@ -212,15 +212,15 @@ through the injector tree until it reaches the root injector.
当类需要某个依赖项时,该依赖项就会作为参数添加到类的构造函数中。
当 Angular 需要实例化该类时,就会调用 DI 框架来提供该依赖。
默认情况下DI 框架会在注入器树中查找一个提供,从该组件的局部注入器开始,如果需要,则沿着注入器树向上冒泡,直到根注入器。
默认情况下DI 框架会在注入器树中查找一个提供,从该组件的局部注入器开始,如果需要,则沿着注入器树向上冒泡,直到根注入器。
* The first injector configured with a provider supplies the dependency (a service instance or value) to the constructor.
第一个配置过该提供的注入器就会把依赖(服务实例或值)提供给这个构造函数。
第一个配置过该提供的注入器就会把依赖(服务实例或值)提供给这个构造函数。
* If no provider is found in the root injector, the DI framework throws an error.
如果在根注入器中也没有找到提供,则 DI 框架将会抛出一个错误。
如果在根注入器中也没有找到提供,则 DI 框架将会抛出一个错误。
There are a number of options for modifying the default search behavior, using _parameter decorators_
on the service-valued parameters of a class constructor.
@ -239,7 +239,7 @@ and walks up the injector tree until it finds the first suitable provider.
Angular throws an error if it can't find the dependency during that walk.
依赖可以注册在组件树的任何层级上。
当组件请求某个依赖时Angular 会从该组件的注入器找起,沿着注入器树向上,直到找到了第一个满足要求的提供。如果没找到依赖Angular 就会抛出一个错误。
当组件请求某个依赖时Angular 会从该组件的注入器找起,沿着注入器树向上,直到找到了第一个满足要求的提供。如果没找到依赖Angular 就会抛出一个错误。
In some cases, you need to limit the search or accommodate a missing dependency.
You can modify Angular's search behavior with the `@Host` and `@Optional` qualifying
@ -320,7 +320,7 @@ The host `HeroBioComponent` doesn't have its own `LoggerService` provider.
另一个 `@Host()` 函数是构造函数属性 `loggerService` 的装饰器。
在本应用程序中只有一个在 `AppComponent` 级提供的 `LoggerService` 实例。
该宿主 `HeroBioComponent` 没有自己的 `LoggerService` 提供
该宿主 `HeroBioComponent` 没有自己的 `LoggerService` 提供
Angular throws an error if you haven't also decorated the property with `@Optional()`.
When the property is marked as optional, Angular sets `loggerService` to null and the rest of the component adapts.
@ -354,11 +354,11 @@ the app throws an exception when it cannot find the required logger at the host
### Supply a custom provider with `@Inject`
### 使用 `@Inject` 指定自定义提供
### 使用 `@Inject` 指定自定义提供
Using a custom provider allows you to provide a concrete implementation for implicit dependencies, such as built-in browser APIs. The following example uses an `InjectionToken` to provide the [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) browser API as a dependency in the `BrowserStorageService`.
自定义提供让你可以为隐式依赖提供一个具体的实现,比如内置浏览器 API。下面的例子使用 `InjectionToken` 来提供 [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage),将其作为 `BrowserStorageService` 的依赖项。
自定义提供让你可以为隐式依赖提供一个具体的实现,比如内置浏览器 API。下面的例子使用 `InjectionToken` 来提供 [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage),将其作为 `BrowserStorageService` 的依赖项。
<code-example path="dependency-injection-in-action/src/app/storage.service.ts" header="src/app/storage.service.ts">
@ -366,13 +366,13 @@ Using a custom provider allows you to provide a concrete implementation for impl
The `factory` function returns the `localStorage` property that is attached to the browser window object. The `Inject` decorator is a constructor parameter used to specify a custom provider of a dependency. This custom provider can now be overridden during testing with a mock API of `localStorage` instead of interacting with real browser APIs.
`factory` 函数返回 window 对象上的 `localStorage` 属性。`Inject` 装饰器修饰一个构造函数参数,用于为某个依赖提供自定义提供。现在,就可以在测试期间使用 `localStorage` 的 Mock API 来覆盖这个提供了,而不必与真实的浏览器 API 进行交互。
`factory` 函数返回 window 对象上的 `localStorage` 属性。`Inject` 装饰器修饰一个构造函数参数,用于为某个依赖提供自定义提供。现在,就可以在测试期间使用 `localStorage` 的 Mock API 来覆盖这个提供了,而不必与真实的浏览器 API 进行交互。
{@a skip}
### Modify the provider search with `@Self` and `@SkipSelf`
### 使用 `@Self``@SkipSelf` 来修改提供的搜索方式
### 使用 `@Self``@SkipSelf` 来修改提供的搜索方式
Providers can also be scoped by injector through constructor parameter decorators. The following example overrides the `BROWSER_STORAGE` token in the `Component` class `providers` with the `sessionStorage` browser API. The same `BrowserStorageService` is injected twice in the constructor, decorated with `@Self` and `@SkipSelf` to define which injector handles the provider dependency.
@ -384,7 +384,7 @@ Providers can also be scoped by injector through constructor parameter decorator
Using the `@Self` decorator, the injector only looks at the component's injector for its providers. The `@SkipSelf` decorator allows you to skip the local injector and look up in the hierarchy to find a provider that satisfies this dependency. The `sessionStorageService` instance interacts with the `BrowserStorageService` using the `sessionStorage` browser API, while the `localStorageService` skips the local injector and uses the root `BrowserStorageService` that uses the `localStorage` browser API.
使用 `@Self` 装饰器时,注入器只在该组件的注入器中查找提供。`@SkipSelf` 装饰器可以让你跳过局部注入器,并在注入器树中向上查找,以发现哪个提供满足该依赖。
使用 `@Self` 装饰器时,注入器只在该组件的注入器中查找提供。`@SkipSelf` 装饰器可以让你跳过局部注入器,并在注入器树中向上查找,以发现哪个提供满足该依赖。
`sessionStorageService` 实例使用浏览器的 `sessionStorage` 来跟 `BrowserStorageService` 打交道,而 `localStorageService` 跳过了局部注入器,使用根注入器提供的 `BrowserStorageService`,它使用浏览器的 `localStorage` API。
{@a component-element}
@ -439,11 +439,11 @@ The following image shows the effect of mousing over the `<hero-bios-and-contact
## Define dependencies with providers
## 使用提供来定义依赖
## 使用提供来定义依赖
This section demonstrates how to write providers that deliver dependent services.
本节会示范如何编写提供来交付被依赖的服务。
本节会示范如何编写提供来交付被依赖的服务。
In order to get a service from a dependency injector, you have to give it a [token](guide/glossary#token).
Angular usually handles this transaction by specifying a constructor parameter and its type.
@ -471,7 +471,7 @@ it provides that instance.
If it doesn't, it needs to make one using the provider associated with the token.
如果注入器已经缓存了与该令牌相关的服务实例,那么它就会直接提供此实例。
如果它没有,它就要使用与该令牌相关的提供来创建一个。
如果它没有,它就要使用与该令牌相关的提供来创建一个。
<div class="alert is-helpful">
@ -479,7 +479,7 @@ If the injector doesn't have a provider for a requested token, it delegates the
to its parent injector, where the process repeats until there are no more injectors.
If the search fails, the injector throws an error&mdash;unless the request was [optional](guide/dependency-injection-in-action#optional).
如果注入器无法根据令牌在自己内部找到对应的提供,它便将请求移交给它的父级注入器,这个过程不断重复,直到没有更多注入器为止。
如果注入器无法根据令牌在自己内部找到对应的提供,它便将请求移交给它的父级注入器,这个过程不断重复,直到没有更多注入器为止。
如果没找到,注入器就抛出一个错误...除非这个请求是[可选的](guide/dependency-injection-in-action#optional)。
</div>
@ -488,22 +488,22 @@ A new injector has no providers.
Angular initializes the injectors it creates with a set of preferred providers.
You have to configure providers for your own app-specific dependencies.
新的注入器没有提供
Angular 会使用一组首选提供来初始化它本身的注入器。
你必须为自己应用程序特有的依赖项来配置提供
新的注入器没有提供
Angular 会使用一组首选提供来初始化它本身的注入器。
你必须为自己应用程序特有的依赖项来配置提供
{@a defining-providers}
### Defining providers
### 定义提供
### 定义提供
A dependency can't always be created by the default method of instantiating a class.
You learned about some other methods in [Dependency Providers](guide/dependency-injection-providers).
The following `HeroOfTheMonthComponent` example demonstrates many of the alternatives and why you need them.
It's visually simple: a few properties and the logs produced by a logger.
用于实例化类的默认方法不一定总适合用来创建依赖。你可以到[依赖提供](guide/dependency-injection-providers)部分查看其它方法。
用于实例化类的默认方法不一定总适合用来创建依赖。你可以到[依赖提供](guide/dependency-injection-providers)部分查看其它方法。
`HeroOfTheMonthComponent` 例子示范了一些替代方案,展示了为什么需要它们。
它看起来很简单:一些属性和一些由 logger 生成的日志。
@ -524,13 +524,13 @@ The use cases illustrate different ways to use the [*provide* object literal](gu
The `providers` array shows how you might use the different provider-definition keys;
`useValue`, `useClass`, `useExisting`, or `useFactory`.
`providers` 数组展示了你可以如何使用其它的键来定义提供`useValue`、`useClass`、`useExisting` 或 `useFactory`
`providers` 数组展示了你可以如何使用其它的键来定义提供`useValue`、`useClass`、`useExisting` 或 `useFactory`
{@a usevalue}
#### Value providers: `useValue`
#### 值提供`useValue`
#### 值提供`useValue`
The `useValue` key lets you associate a fixed value with a DI token.
Use this technique to provide *runtime configuration constants* such as website base addresses and feature flags.
@ -538,11 +538,11 @@ You can also use a value provider in a unit test to provide mock data in place o
`useValue` 键让你可以为 DI 令牌关联一个固定的值。
使用该技巧来进行*运行期常量设置*,比如网站的基础地址和功能标志等。
你也可以在单元测试中使用*值提供*,来用一个 Mock 数据来代替一个生产环境下的数据服务。
你也可以在单元测试中使用*值提供*,来用一个 Mock 数据来代替一个生产环境下的数据服务。
The `HeroOfTheMonthComponent` example has two value providers.
`HeroOfTheMonthComponent` 例子中有两个*值-提供*。
`HeroOfTheMonthComponent` 例子中有两个*值-提供*。
<code-example path="dependency-injection-in-action/src/app/hero-of-the-month.component.ts" region="use-value" header="dependency-injection-in-action/src/app/hero-of-the-month.component.ts"></code-example>
@ -558,19 +558,19 @@ special kind of provider lookup key called an [injection token](guide/dependency
an `InjectionToken` instance.
第二处为 `TITLE` 令牌指定了一个字符串字面量资源。
`TITLE` 提供商的令牌*不是一个类*,而是一个特别的提供商查询键,名叫[InjectionToken](guide/dependency-injection-in-action#injection-token),表示一个 `InjectionToken` 实例。
`TITLE` 提供者的令牌*不是一个类*,而是一个特别的提供者查询键,名叫[InjectionToken](guide/dependency-injection-in-action#injection-token),表示一个 `InjectionToken` 实例。
You can use an injection token for any kind of provider but it's particularly
helpful when the dependency is a simple value like a string, a number, or a function.
你可以把 `InjectionToken` 用作任何类型的提供的令牌,但是当依赖是简单类型(比如字符串、数字、函数)时,它会特别有用。
你可以把 `InjectionToken` 用作任何类型的提供的令牌,但是当依赖是简单类型(比如字符串、数字、函数)时,它会特别有用。
The value of a *value provider* must be defined before you specify it here.
The title string literal is immediately available.
The `someHero` variable in this example was set earlier in the file as shown below.
You can't use a variable whose value will be defined later.
一个*值-提供*的值必须在指定之前定义。
一个*值-提供*的值必须在指定之前定义。
比如标题字符串就是立即可用的。
该例中的 `someHero` 变量是以前在如下的文件中定义的。
你不能使用那些要等以后才能定义其值的变量。
@ -581,13 +581,13 @@ You can't use a variable whose value will be defined later.
Other types of providers can create their values *lazily*; that is, when they're needed for injection.
其它类型的提供都会*惰性创建*它们的值,也就是说只在需要注入它们的时候才创建。
其它类型的提供都会*惰性创建*它们的值,也就是说只在需要注入它们的时候才创建。
{@a useclass}
#### Class providers: `useClass`
#### 类提供`useClass`
#### 类提供`useClass`
The `useClass` provider key lets you create and return a new instance of the specified class.
@ -598,7 +598,7 @@ for a common or default class.
The alternative implementation could, for example, implement a different strategy,
extend the default class, or emulate the behavior of the real class in a test case.
你可以使用这类提供来为公共类或默认类换上一个*替代实现*。比如,这个替代实现可以实现一种不同的策略来扩展默认类,或在测试环境中模拟真实类的行为。
你可以使用这类提供来为公共类或默认类换上一个*替代实现*。比如,这个替代实现可以实现一种不同的策略来扩展默认类,或在测试环境中模拟真实类的行为。
The following code shows two examples in `HeroOfTheMonthComponent`.
@ -610,14 +610,14 @@ The first provider is the *de-sugared*, expanded form of the most typical case i
class to be created (`HeroService`) is also the provider's dependency injection token.
The short form is generally preferred; this long form makes the details explicit.
第一个提供是*展开了语法糖的*,是一个典型情况的展开。一般来说,被新建的类(`HeroService`)同时也是该提供的注入令牌。
第一个提供是*展开了语法糖的*,是一个典型情况的展开。一般来说,被新建的类(`HeroService`)同时也是该提供的注入令牌。
通常都选用缩写形式,完整形式可以让细节更明确。
The second provider substitutes `DateLoggerService` for `LoggerService`.
`LoggerService` is already registered at the `AppComponent` level.
When this child component requests `LoggerService`, it receives a `DateLoggerService` instance instead.
第二个提供使用 `DateLoggerService` 来满足 `LoggerService`。该 `LoggerService``AppComponent` 级别已经被注册。当*这个组件*要求 `LoggerService` 的时候,它得到的却是 `DateLoggerService` 服务的实例。
第二个提供使用 `DateLoggerService` 来满足 `LoggerService`。该 `LoggerService``AppComponent` 级别已经被注册。当*这个组件*要求 `LoggerService` 的时候,它得到的却是 `DateLoggerService` 服务的实例。
<div class="alert is-helpful">
@ -638,7 +638,7 @@ Components outside the tree continue to receive the original `LoggerService` ins
#### Alias providers: `useExisting`
#### 别名提供`useExisting`
#### 别名提供`useExisting`
The `useExisting` provider key lets you map one token to another.
In effect, the first token is an *alias* for the service associated with the second token,
@ -697,7 +697,7 @@ This is illustrated in the following image, which displays the logging date.
#### Factory providers: `useFactory`
#### 工厂提供`useFactory`
#### 工厂提供`useFactory`
The `useFactory` provider key lets you create a dependency object by calling a factory function,
as in the following example.
@ -714,7 +714,7 @@ Notice that this form of provider has a third key, `deps`, which specifies
dependencies for the `useFactory` function.
注入器通过调用你用 `useFactory` 键指定的工厂函数来提供该依赖的值。
注意,提供的这种形态还有第三个键 `deps`,它指定了供 `useFactory` 函数使用的那些依赖。
注意,提供的这种形态还有第三个键 `deps`,它指定了供 `useFactory` 函数使用的那些依赖。
Use this technique to create a dependency object with a factory function
whose inputs are a combination of *injected services* and *local state*.
@ -736,14 +736,14 @@ the passed-in state value and the injected services `Hero` and `HeroService`.
在这个例子中,局部状态是数字 `2`,也就是组件应该显示的参赛者数量。
该状态的值传给了 `runnersUpFactory()` 作为参数。
`runnersUpFactory()` 返回了*提供的工厂函数*,它可以使用传入的状态值和注入的服务 `Hero``HeroService`
`runnersUpFactory()` 返回了*提供的工厂函数*,它可以使用传入的状态值和注入的服务 `Hero``HeroService`
<code-example path="dependency-injection-in-action/src/app/runners-up.ts" region="factory-synopsis" header="runners-up.ts (excerpt)"></code-example>
The provider factory function (returned by `runnersUpFactory()`) returns the actual dependency object,
the string of names.
`runnersUpFactory()` 返回的提供的工厂函数返回了实际的依赖对象,也就是表示名字的字符串。
`runnersUpFactory()` 返回的提供的工厂函数返回了实际的依赖对象,也就是表示名字的字符串。
* The function takes a winning `Hero` and a `HeroService` as arguments.
@ -797,7 +797,7 @@ That's the subject of the next section.
The previous *Hero of the Month* example used the `MinimalLogger` class
as the token for a provider of `LoggerService`.
前面的*月度英雄*的例子使用了 `MinimalLogger` 类作为 `LoggerService` 提供的令牌。
前面的*月度英雄*的例子使用了 `MinimalLogger` 类作为 `LoggerService` 提供的令牌。
<code-example path="dependency-injection-in-action/src/app/hero-of-the-month.component.ts" region="use-existing" header="dependency-injection-in-action/src/app/hero-of-the-month.component.ts">
@ -830,7 +830,7 @@ When you use a class this way, it's called a *class interface*.
As mentioned in [DI Providers](guide/dependency-injection-providers#interface-not-valid-token), an interface is not a valid DI token because it is a TypeScript artifact that doesn't exist at run time. Use this abstract class interface to get the strong typing of an interface, and also use it as a provider token in the way you would a normal class.
就像 [DI 提供](guide/dependency-injection-providers#interface-not-valid-token)中提到的那样,接口不是有效的 DI 令牌,因为它是 TypeScript 自己用的,在运行期间不存在。使用这种抽象类接口不但可以获得像接口一样的强类型,而且可以像普通类一样把它用作提供令牌。
就像 [DI 提供](guide/dependency-injection-providers#interface-not-valid-token)中提到的那样,接口不是有效的 DI 令牌,因为它是 TypeScript 自己用的,在运行期间不存在。使用这种抽象类接口不但可以获得像接口一样的强类型,而且可以像普通类一样把它用作提供令牌。
A class interface should define *only* the members that its consumers are allowed to call.
Such a narrowing interface helps decouple the concrete class from its consumers.
@ -880,7 +880,7 @@ another token that happens to have the same name.
You encountered them twice in the *Hero of the Month* example,
in the *title* value provider and in the *runnersUp* factory provider.
`InjectionToken` 具有这些特征。在*Hero of the Month*例子中遇见它们两次,一个是 *title* 的值,一个是 *runnersUp* 工厂提供
`InjectionToken` 具有这些特征。在*Hero of the Month*例子中遇见它们两次,一个是 *title* 的值,一个是 *runnersUp* 工厂提供
<code-example path="dependency-injection-in-action/src/app/hero-of-the-month.component.ts" region="provide-injection-token" header="dependency-injection-in-action/src/app/hero-of-the-month.component.ts"></code-example>

View File

@ -176,7 +176,7 @@ You can find a parent component with a [class interface](guide/dependency-inject
The parent must cooperate by providing an *alias* to itself in the name of a class interface token.
该父组件必须合作,以类接口令牌为名,为自己定义一个*别名提供*。
该父组件必须合作,以类接口令牌为名,为自己定义一个*别名提供*。
Recall that Angular always adds a component instance to its own injector;
that's why you could inject *Alex* into *Cathy* [earlier](#known-parent).
@ -187,7 +187,7 @@ Write an [*alias provider*](guide/dependency-injection-in-action#useexisting)&md
definition&mdash;that creates an *alternative* way to inject the same component instance
and add that provider to the `providers` array of the `@Component()` metadata for the `AlexComponent`.
编写一个 [*别名提供*](guide/dependency-injection-in-action#useexisting)(一个 `provide` 对象字面量,其中有一个 `useExisting` 定义),创造了另一种方式来注入同一个组件实例,并把那个提供添加到 `AlexComponent` `@Component()` 元数据的 `providers` 数组中。
编写一个 [*别名提供*](guide/dependency-injection-in-action#useexisting)(一个 `provide` 对象字面量,其中有一个 `useExisting` 定义),创造了另一种方式来注入同一个组件实例,并把那个提供添加到 `AlexComponent` `@Component()` 元数据的 `providers` 数组中。
{@a alex-providers}
@ -198,7 +198,7 @@ and add that provider to the `providers` array of the `@Component()` metadata fo
[Parent](#parent-token) is the provider's class interface token.
The [*forwardRef*](guide/dependency-injection-in-action#forwardref) breaks the circular reference you just created by having the `AlexComponent` refer to itself.
[Parent](#parent-token) 是该提供的类接口。
[Parent](#parent-token) 是该提供的类接口。
[*forwardRef*](guide/dependency-injection-in-action#forwardref) 用于打破循环引用,因为在你刚才这个定义中 `AlexComponent` 引用了自身。
*Carol*, the third of *Alex*'s child components, injects the parent into its `parent` parameter,
@ -252,7 +252,7 @@ Here's *Barry*.
If you're going to keep writing [*alias providers*](guide/dependency-injection-in-action#useexisting) like this you should create a [helper function](#provideparent).
*Barry* 的 `providers` 数组看起来和 [*Alex*](#alex-providers) 的一样。
如果你准备继续像这样编写[*别名提供*](guide/dependency-injection-in-action#useexisting),就应该创建一个[辅助函数](#provideparent)。
如果你准备继续像这样编写[*别名提供*](guide/dependency-injection-in-action#useexisting),就应该创建一个[辅助函数](#provideparent)。
For now, focus on *Barry*'s constructor.
@ -368,7 +368,7 @@ It doesn't in this example *only* to demonstrate that the code will compile and
Writing variations of the same parent *alias provider* gets old quickly,
especially this awful mouthful with a [*forwardRef*](guide/dependency-injection-in-action#forwardref).
你很快就会厌倦为同一个父组件编写*别名提供*的变体形式,特别是带有 [*forwardRef*](guide/dependency-injection-in-action#forwardref) 的那种。
你很快就会厌倦为同一个父组件编写*别名提供*的变体形式,特别是带有 [*forwardRef*](guide/dependency-injection-in-action#forwardref) 的那种。
<code-example path="dependency-injection-in-action/src/app/parent-finder.component.ts" region="alex-providers" header="dependency-injection-in-action/src/app/parent-finder.component.ts"></code-example>
@ -380,7 +380,7 @@ You can extract that logic into a helper function like the following.
Now you can add a simpler, more meaningful parent provider to your components.
现在,你可以为组件添加一个更简单、更有意义的父组件提供
现在,你可以为组件添加一个更简单、更有意义的父组件提供
<code-example path="dependency-injection-in-action/src/app/parent-finder.component.ts" region="alice-providers" header="dependency-injection-in-action/src/app/parent-finder.component.ts"></code-example>

View File

@ -1,6 +1,6 @@
# Dependency providers
# 依赖提供
# 依赖提供
A dependency [provider](guide/glossary#provider) configures an injector
with a [DI token](guide/glossary#di-token),
@ -8,14 +8,14 @@ which that injector uses to provide the concrete, runtime version of a dependenc
The injector relies on the provider configuration to create instances of the dependencies
that it injects into components, directives, pipes, and other services.
依赖[提供](guide/glossary#provider)会使用 [DI 令牌](guide/glossary#di-token)来配置注入器,注入器会用它来提供这个依赖值的具体的、运行时版本。
注入器依靠 "提供配置" 来创建依赖的实例,并把该实例注入到组件、指令、管道和其它服务中。
依赖[提供](guide/glossary#provider)会使用 [DI 令牌](guide/glossary#di-token)来配置注入器,注入器会用它来提供这个依赖值的具体的、运行时版本。
注入器依靠 "提供配置" 来创建依赖的实例,并把该实例注入到组件、指令、管道和其它服务中。
You must configure an injector with a provider, or it won't know how to create the dependency.
The most obvious way for an injector to create an instance of a service class is with the class itself.
If you specify the service class itself as the provider token, the default behavior is for the injector to instantiate that class with `new`.
你必须使用提供来配置注入器,否则注入器就无法知道如何创建此依赖。
你必须使用提供来配置注入器,否则注入器就无法知道如何创建此依赖。
注入器创建服务实例的最简单方法,就是用这个服务类本身来创建它。
如果你把服务类作为此服务的 DI 令牌,注入器的默认行为就是 `new` 出这个类实例。
@ -30,7 +30,7 @@ You can, however, configure an injector with an alternative provider,
in order to deliver some other object that provides the needed logging functionality.
For instance:
不过,你也可以用一个替代提供来配置注入器,这样就可以指定另一些同样能提供日志功能的对象。
不过,你也可以用一个替代提供来配置注入器,这样就可以指定另一些同样能提供日志功能的对象。
比如:
* You can provide a substitute class.
@ -43,7 +43,7 @@ For instance:
* Your provider can call a logger factory function.
你的提供可以调用一个工厂函数来创建 logger。
你的提供可以调用一个工厂函数来创建 logger。
{@a provide}
@ -55,8 +55,8 @@ The class-provider syntax is a shorthand expression that expands
into a provider configuration, defined by the [`Provider` interface](api/core/Provider).
The following code snippets shows how a class that is given as the `providers` value is expanded into a full provider object.
类提供的语法实际上是一种简写形式,它会扩展成一个由 [`Provider` 接口](api/core/Provider)定义的提供配置对象。
下面的代码片段展示了 `providers` 中给出的类会如何扩展成完整的提供配置对象。
类提供的语法实际上是一种简写形式,它会扩展成一个由 [`Provider` 接口](api/core/Provider)定义的提供配置对象。
下面的代码片段展示了 `providers` 中给出的类会如何扩展成完整的提供配置对象。
<code-example path="dependency-injection/src/app/providers.component.ts" region="providers-logger">
</code-example>
@ -66,7 +66,7 @@ The following code snippets shows how a class that is given as the `providers` v
The expanded provider configuration is an object literal with two properties.
扩展的提供配置是一个具有两个属性的对象字面量。
扩展的提供配置是一个具有两个属性的对象字面量。
* The `provide` property holds the [token](guide/dependency-injection#token)
that serves as the key for both locating a dependency value and configuring the injector.
@ -78,8 +78,8 @@ The provider-definition key can be `useClass`, as in the example.
It can also be `useExisting`, `useValue`, or `useFactory`.
Each of these keys provides a different type of dependency, as discussed below.
第二个属性是一个提供定义对象,它告诉注入器要如何创建依赖值。
提供定义对象中的 key 可以是 `useClass` —— 就像这个例子中一样。
第二个属性是一个提供定义对象,它告诉注入器要如何创建依赖值。
提供定义对象中的 key 可以是 `useClass` —— 就像这个例子中一样。
也可以是 `useExisting`、`useValue` 或 `useFactory`
每一个 key 都用于提供一种不同类型的依赖,我们稍后会讨论。
@ -87,7 +87,7 @@ Each of these keys provides a different type of dependency, as discussed below.
## Alternative class providers
## 替代类提供
## 替代类提供
Different classes can provide the same service.
For example, the following code tells the injector
@ -104,7 +104,7 @@ using the `Logger` token.
### Class providers with dependencies
### 带依赖的类提供
### 带依赖的类提供
Another class, `EvenBetterLogger`, might display the user name in the log message.
This logger gets the user from an injected `UserService` instance.
@ -117,8 +117,8 @@ This logger gets the user from an injected `UserService` instance.
The injector needs providers for both this new logging service and its dependent `UserService`. Configure this alternative logger with the `useClass` provider-definition key, like `BetterLogger`. The following array specifies both providers in the `providers` metadata option of the parent module or component.
注入器需要提供这个新的日志服务以及该服务所依赖的 `UserService` 对象。
使用 `useClass` 作为提供定义对象的 key ,来配置一个 logger 的替代品,比如 `BetterLogger`
下面的数组同时在父模块和组件的 `providers` 元数据选项中指定了这些提供
使用 `useClass` 作为提供定义对象的 key ,来配置一个 logger 的替代品,比如 `BetterLogger`
下面的数组同时在父模块和组件的 `providers` 元数据选项中指定了这些提供
<code-example path="dependency-injection/src/app/providers.component.ts" region="providers-5"></code-example>
@ -126,7 +126,7 @@ The injector needs providers for both this new logging service and its dependent
### Aliased class providers
### 别名类提供
### 别名类提供
Suppose an old component depends upon the `OldLogger` class.
`OldLogger` has the same interface as `NewLogger`, but for some reason
@ -160,7 +160,7 @@ To make sure there is only one instance of `NewLogger`, alias `OldLogger` with t
## Value providers
## 值提供
## 值提供
Sometimes it's easier to provide a ready-made object rather than ask the injector to create it from a class.
To inject an object you have already created,
@ -177,7 +177,7 @@ The following code defines a variable that creates such an object to play the lo
The following provider object uses the `useValue` key to associate the variable with the `Logger` token.
下面的提供定义对象使用 `useValue` 作为 key 来把该变量与 `Logger` 令牌关联起来。
下面的提供定义对象使用 `useValue` 作为 key 来把该变量与 `Logger` 令牌关联起来。
<code-example path="dependency-injection/src/app/providers.component.ts" region="providers-7"></code-example>
@ -244,7 +244,7 @@ Another solution to choosing a provider token for non-class dependencies is
to define and use an `InjectionToken` object.
The following example shows how to define such a token.
另一个为非类依赖选择提供令牌的解决方案是定义并使用 `InjectionToken` 对象。
另一个为非类依赖选择提供令牌的解决方案是定义并使用 `InjectionToken` 对象。
下面的例子展示了如何定义那样一个令牌。
<code-example path="dependency-injection/src/app/app.config.ts" region="token" header="src/app/app.config.ts"></code-example>
@ -257,7 +257,7 @@ The token description is another developer aid.
Register the dependency provider using the `InjectionToken` object:
使用 `InjectionToken` 对象注册依赖提供
使用 `InjectionToken` 对象注册依赖提供
<code-example path="dependency-injection/src/app/providers.component.ts" region="providers-9"></code-example>
@ -283,7 +283,7 @@ it supports typing of the configuration object within the class.
## Factory providers
## 工厂提供
## 工厂提供
Sometimes you need to create a dependent value dynamically,
based on information you won't have until run time.
@ -296,8 +296,8 @@ Also, your injectable service might not have independent access to the source of
In cases like this you can use a *factory provider*.
Factory providers can also be useful when creating an instance of a dependency from a third-party library that wasn't designed to work with DI.
这种情况下,你可以使用*工厂提供*。
当需要从第三方库创建依赖项实例时,工厂提供也很有用,因为第三方库不是为 DI 而设计的。
这种情况下,你可以使用*工厂提供*。
当需要从第三方库创建依赖项实例时,工厂提供也很有用,因为第三方库不是为 DI 而设计的。
For example, suppose `HeroService` must hide *secret* heroes from normal users.
Only authorized users should see secret heroes.
@ -326,11 +326,11 @@ To resolve this, we give the `HeroService` constructor a boolean flag to control
You can inject `Logger`, but you can't inject the `isAuthorized` flag. Instead, you can use a factory provider to create a new logger instance for `HeroService`.
你可以注入 `Logger` 但是不能注入 `isAuthorized` 标志。不过你可以改用工厂提供来为 `HeroService` 创建一个新的 logger 实例。
你可以注入 `Logger` 但是不能注入 `isAuthorized` 标志。不过你可以改用工厂提供来为 `HeroService` 创建一个新的 logger 实例。
A factory provider needs a factory function.
工厂提供需要一个工厂函数。
工厂提供需要一个工厂函数。
<code-example path="dependency-injection/src/app/heroes/hero.service.provider.ts" region="factory" header="src/app/heroes/hero.service.provider.ts (excerpt)"></code-example>
@ -339,20 +339,20 @@ You inject both `Logger` and `UserService` into the factory provider
and let the injector pass them along to the factory function.
虽然 `HeroService` 不能访问 `UserService`,但是工厂函数可以。
你把 `Logger``UserService` 注入到了工厂提供中,并让注入器把它们传给这个工厂函数。
你把 `Logger``UserService` 注入到了工厂提供中,并让注入器把它们传给这个工厂函数。
<code-example path="dependency-injection/src/app/heroes/hero.service.provider.ts" region="provider" header="src/app/heroes/hero.service.provider.ts (excerpt)"></code-example>
* The `useFactory` field tells Angular that the provider is a factory function whose implementation is `heroServiceFactory`.
`useFactory` 字段告诉 Angular 该提供是一个工厂函数,该函数的实现代码是 `heroServiceFactory`
`useFactory` 字段告诉 Angular 该提供是一个工厂函数,该函数的实现代码是 `heroServiceFactory`
* The `deps` property is an array of [provider tokens](guide/dependency-injection#token).
The `Logger` and `UserService` classes serve as tokens for their own class providers.
The injector resolves these tokens and injects the corresponding services into the matching factory function parameters.
`deps` 属性是一个[提供令牌](guide/dependency-injection#token)数组。
`Logger``UserService` 类作为它们自己的类提供令牌使用。
`deps` 属性是一个[提供令牌](guide/dependency-injection#token)数组。
`Logger``UserService` 类作为它们自己的类提供令牌使用。
注入器解析这些令牌,并把与之对应的服务注入到相应的工厂函数参数表中。
Notice that you captured the factory provider in an exported variable, `heroServiceProvider`.
@ -361,9 +361,9 @@ You can configure a provider of `HeroService` with this variable wherever you ne
In this sample, you need it only in `HeroesComponent`,
where `heroServiceProvider` replaces `HeroService` in the metadata `providers` array.
注意,你把这个工厂提供保存到了一个导出的变量 `heroServiceProvider` 中。
这个额外的步骤让工厂提供可被复用。
你可以在任何需要它的地方用这个变量来配置 `HeroService` 的提供
注意,你把这个工厂提供保存到了一个导出的变量 `heroServiceProvider` 中。
这个额外的步骤让工厂提供可被复用。
你可以在任何需要它的地方用这个变量来配置 `HeroService` 的提供
在这个例子中,你只在 `HeroesComponent` 中用到了它。你在该组件元数据的 `providers` 数组中用 `heroServiceProvider` 替换了 `HeroService`
The following shows the new and the old implementations side-by-side.
@ -382,7 +382,7 @@ The following shows the new and the old implementations side-by-side.
## Predefined tokens and multiple providers
## 预定义令牌与多提供
## 预定义令牌与多提供
Angular provides a number of built-in injection-token constants that you can use to customize the behavior of
various systems.
@ -393,7 +393,7 @@ For example, you can use the following built-in tokens as hooks into the framewo
A provider object can associate any of these injection tokens with one or more callback functions that take app-specific initialization actions.
比如,你可以使用下列内置令牌来切入 Angular 框架的启动和初始化过程。
提供对象可以把任何一个注入令牌与一个或多个用来执行应用初始化操作的回调函数关联起来。
提供对象可以把任何一个注入令牌与一个或多个用来执行应用初始化操作的回调函数关联起来。
* [PLATFORM_INITIALIZER](api/core/PLATFORM_INITIALIZER): Callback is invoked when a platform is initialized.
@ -410,7 +410,7 @@ A provider object can associate any of these injection tokens with one or more c
The provider object can have a third option, `multi: true`, which you can use with `APP_INITIALIZER`
to register multiple handlers for the provide event.
该提供对象还有第三个选项 `multi: true`,把它和 `APP_INITIALIZER` 一起使用可以为特定的事件注册多个处理器。
该提供对象还有第三个选项 `multi: true`,把它和 `APP_INITIALIZER` 一起使用可以为特定的事件注册多个处理器。
For example, when bootstrapping an application, you can register many initializers using the same token.
@ -429,8 +429,8 @@ For example, you can register a custom form validator using the built-in [NG_VAL
and provide multiple instances of a given validator provider by using the `multi: true` property in the provider object.
Angular adds your custom validators to the existing collection.
在其它地方,多个提供也同样可以和单个令牌关联起来。
比如,你可以使用内置的 [NG_VALIDATORS](api/forms/NG_VALIDATORS) 令牌注册自定义表单验证器,还可以在提供定义对象中使用 `multi: true` 属性来为指定的验证器令牌提供多个验证器实例。
在其它地方,多个提供也同样可以和单个令牌关联起来。
比如,你可以使用内置的 [NG_VALIDATORS](api/forms/NG_VALIDATORS) 令牌注册自定义表单验证器,还可以在提供定义对象中使用 `multi: true` 属性来为指定的验证器令牌提供多个验证器实例。
Angular 会把你的自定义验证器添加到现有验证器的集合中。
The Router also makes use of multiple providers associated with a single token.
@ -438,7 +438,7 @@ When you provide multiple sets of routes using [RouterModule.forRoot](api/router
and [RouterModule.forChild](api/router/RouterModule#forchild) in a single module,
the [ROUTES](api/router/ROUTES) token combines all the different provided sets of routes into a single value.
路由器也同样用多个提供关联到了一个令牌。
路由器也同样用多个提供关联到了一个令牌。
当你在单个模块中用 [RouterModule.forRoot](api/router/RouterModule#forroot) 和 [RouterModule.forChild](api/router/RouterModule#forchild) 提供了多组路由时,[ROUTES](api/router/ROUTES) 令牌会把这些不同的路由组都合并成一个单一值。
<div class="alert is-helpful">
@ -454,7 +454,7 @@ Search for [Constants in API documentation](api?type=const) to find more built-i
## Tree-shakable providers
## 可摇树优化的提供
## 可摇树优化的提供
Tree shaking refers to a compiler option that removes code from the final bundle if the app doesn't reference that code.
When providers are tree-shakable, the Angular compiler removes the associated
@ -462,7 +462,7 @@ services from the final output when it determines that your application doesn't
This significantly reduces the size of your bundles.
摇树优化是指一个编译器选项,意思是把应用中未引用过的代码从最终生成的包中移除。
如果提供是可摇树优化的Angular 编译器就会从最终的输出内容中移除应用代码中从未用过的服务。
如果提供是可摇树优化的Angular 编译器就会从最终的输出内容中移除应用代码中从未用过的服务。
这会显著减小你的打包体积。
<div class="alert is-helpful">
@ -483,7 +483,7 @@ Thus, services in the NgModule `providers` array or at component level are not t
The following example of non-tree-shakable providers in Angular configures a service provider for the injector of an NgModule.
下面这个不可摇树优化的 Angular 提供商的例子为 NgModule 注入器配置了一个服务提供商
下面这个不可摇树优化的 Angular 提供者的例子为 NgModule 注入器配置了一个服务提供者
<code-example path="dependency-injection/src/app/tree-shaking/service-and-module.ts" header="src/app/tree-shaking/service-and-modules.ts"></code-example>
@ -497,19 +497,19 @@ as in the following example.
When `ngc` runs, it compiles `AppModule` into a module factory, which contains definitions for all the providers declared in all the modules it includes. At runtime, this factory becomes an injector that instantiates these services.
当运行 `ngc` 时,它会把 `AppModule` 编译到模块工厂中,工厂包含该模块及其导入的所有模块中声明的所有提供。在运行时,该工厂会变成负责实例化所有这些服务的注入器。
当运行 `ngc` 时,它会把 `AppModule` 编译到模块工厂中,工厂包含该模块及其导入的所有模块中声明的所有提供。在运行时,该工厂会变成负责实例化所有这些服务的注入器。
Tree-shaking doesn't work here because Angular can't decide to exclude one chunk of code (the provider definition for the service within the module factory) based on whether another chunk of code (the service class) is used. To make services tree-shakable, the information about how to construct an instance of the service (the provider definition) needs to be a part of the service class itself.
这里摇树优化不起作用,因为 Angular 无法根据是否用到了其它代码块(服务类),来决定是否能排除这块代码(模块工厂中的服务提供定义)。要让服务可以被摇树优化,关于如何构建该服务实例的信息(即提供定义),就应该是服务类本身的一部分。
这里摇树优化不起作用,因为 Angular 无法根据是否用到了其它代码块(服务类),来决定是否能排除这块代码(模块工厂中的服务提供定义)。要让服务可以被摇树优化,关于如何构建该服务实例的信息(即提供定义),就应该是服务类本身的一部分。
### Creating tree-shakable providers
### 创建可摇树优化的提供
### 创建可摇树优化的提供
You can make a provider tree-shakable by specifying it in the `@Injectable()` decorator on the service itself, rather than in the metadata for the NgModule or component that depends on the service.
只要在服务本身的 `@Injectable()` 装饰器中指定,而不是在依赖该服务的 NgModule 或组件的元数据中指定,你就可以制作一个可摇树优化的提供
只要在服务本身的 `@Injectable()` 装饰器中指定,而不是在依赖该服务的 NgModule 或组件的元数据中指定,你就可以制作一个可摇树优化的提供
The following example shows the tree-shakable equivalent to the `ServiceModule` example above.
@ -527,6 +527,6 @@ The service can be instantiated by configuring a factory function, as in the fol
To override a tree-shakable provider, configure the injector of a specific NgModule or component with another provider, using the `providers: []` array syntax of the `@NgModule()` or `@Component()` decorator.
要想覆盖可摇树优化的提供商,请使用其它提供商来配置指定的 NgModule 或组件的注入器,只要使用 `@NgModule()``@Component()` 装饰器中的 `providers: []` 数组就可以了。
要想覆盖可摇树优化的提供者,请使用其它提供者来配置指定的 NgModule 或组件的注入器,只要使用 `@NgModule()``@Component()` 装饰器中的 `providers: []` 数组就可以了。
</div>

View File

@ -76,7 +76,7 @@ replace every use of the `HEROES` mock data.
The DI framework lets you supply data to a component from an injectable _service_ class, defined in its own file. To demonstrate, we'll create an injectable service class that provides a list of heroes, and register that class as a provider of that service.
DI 框架让你能从一个可注入的*服务*类(独立文件)中为组件提供数据。为了演示,我们还会创建一个用来提供英雄列表的、可注入的服务类,并把它注册为该服务的提供
DI 框架让你能从一个可注入的*服务*类(独立文件)中为组件提供数据。为了演示,我们还会创建一个用来提供英雄列表的、可注入的服务类,并把它注册为该服务的提供
<div class="alert is-helpful">
@ -132,13 +132,13 @@ The `@Injectable()` is an essential ingredient in every Angular service definiti
### Configure an injector with a service provider
### 用服务提供配置注入器
### 用服务提供配置注入器
The class we have created provides a service. The `@Injectable()` decorator marks it as a service
that can be injected, but Angular can't actually inject it anywhere until you configure
an Angular [dependency injector](guide/glossary#injector) with a [provider](guide/glossary#provider) of that service.
我们创建的类提供了一个服务。`@Injectable()` 装饰器把它标记为可供注入的服务,不过在你使用该服务的 [provider](guide/glossary#provider) 提供配置好 Angular 的[依赖注入器](guide/glossary#injector)之前Angular 实际上无法将其注入到任何位置。
我们创建的类提供了一个服务。`@Injectable()` 装饰器把它标记为可供注入的服务,不过在你使用该服务的 [provider](guide/glossary#provider) 提供配置好 Angular 的[依赖注入器](guide/glossary#injector)之前Angular 实际上无法将其注入到任何位置。
The injector is responsible for creating service instances and injecting them into classes like `HeroListComponent`.
You rarely create an Angular injector yourself. Angular creates injectors for you as it executes the app, starting with the _root injector_ that it creates during the [bootstrap process](guide/bootstrapping).
@ -149,15 +149,15 @@ You rarely create an Angular injector yourself. Angular creates injectors for yo
A provider tells an injector _how to create the service_.
You must configure an injector with a provider before that injector can create a service (or provide any other kind of dependency).
提供会告诉注入器*如何创建该服务*。
要想让注入器能够创建服务(或提供其它类型的依赖),你必须使用某个提供配置好注入器。
提供会告诉注入器*如何创建该服务*。
要想让注入器能够创建服务(或提供其它类型的依赖),你必须使用某个提供配置好注入器。
A provider can be the service class itself, so that the injector can use `new` to create an instance.
You might also define more than one class to provide the same service in different ways,
and configure different injectors with different providers.
提供可以是服务类本身,因此注入器可以使用 `new` 来创建实例。
你还可以定义多个类,以不同的方式提供同一个服务,并使用不同的提供来配置不同的注入器。
提供可以是服务类本身,因此注入器可以使用 `new` 来创建实例。
你还可以定义多个类,以不同的方式提供同一个服务,并使用不同的提供来配置不同的注入器。
<div class="alert is-helpful">
@ -172,7 +172,7 @@ from the injector of its parent NgModule, or from the `root` injector.
* Learn more about the [different kinds of providers](guide/dependency-injection-providers).
更多知识,参见 [提供的不同类型](guide/dependency-injection-providers)。
更多知识,参见 [提供的不同类型](guide/dependency-injection-providers)。
* Learn more about how the [injector hierarchy](guide/hierarchical-dependency-injection) works.
@ -182,7 +182,7 @@ from the injector of its parent NgModule, or from the `root` injector.
You can configure injectors with providers at different levels of your app, by setting a metadata value in one of three places:
你可以在三种位置之一设置元数据,以便在应用的不同层级使用提供来配置注入器:
你可以在三种位置之一设置元数据,以便在应用的不同层级使用提供来配置注入器:
* In the `@Injectable()` decorator for the service itself.
@ -198,7 +198,7 @@ You can configure injectors with providers at different levels of your app, by s
The `@Injectable()` decorator has the `providedIn` metadata option, where you can specify the provider of the decorated service class with the `root` injector, or with the injector for a specific NgModule.
`@Injectable()` 装饰器具有一个名叫 `providedIn` 的元数据选项,在那里你可以指定把被装饰类的提供放到 `root` 注入器中,或某个特定 NgModule 的注入器中。
`@Injectable()` 装饰器具有一个名叫 `providedIn` 的元数据选项,在那里你可以指定把被装饰类的提供放到 `root` 注入器中,或某个特定 NgModule 的注入器中。
The `@NgModule()` and `@Component()` decorators have the `providers` metadata option, where you can configure providers for NgModule-level or component-level injectors.
@ -209,11 +209,11 @@ The `@NgModule()` and `@Component()` decorators have the `providers` metadata op
Components are directives, and the `providers` option is inherited from `@Directive()`. You can also configure providers for directives and pipes at the same level as the component.
所有组件都是指令,而 `providers` 选项是从 `@Directive()` 中继承来的。
你也可以与组件一样的级别为指令、管道配置提供
你也可以与组件一样的级别为指令、管道配置提供
Learn more about [where to configure providers](guide/hierarchical-dependency-injection).
欲知详情,参见[该在哪里配置提供](guide/hierarchical-dependency-injection)。
欲知详情,参见[该在哪里配置提供](guide/hierarchical-dependency-injection)。
</div>
@ -270,7 +270,7 @@ Services are singletons _within the scope of an injector_. That is, there is at
There is only one root injector for an app. Providing `UserService` at the `root` or `AppModule` level means it is registered with the root injector. There is just one `UserService` instance in the entire app and every class that injects `UserService` gets this service instance _unless_ you configure another provider with a _child injector_.
应用只有一个根注入器。在 `root``AppModule` 级提供 `UserService` 意味着它注册到了根注入器上。
在整个应用中只有一个 `UserService` 实例,每个要求注入 `UserService` 的类都会得到这一个服务实例,*除非*你在*子注入器*中配置了另一个提供
在整个应用中只有一个 `UserService` 实例,每个要求注入 `UserService` 的类都会得到这一个服务实例,*除非*你在*子注入器*中配置了另一个提供
Angular DI has a [hierarchical injection system](guide/hierarchical-dependency-injection), which means that nested injectors can create their own service instances.
Angular regularly creates nested injectors. Whenever Angular creates a new instance of a component that has `providers` specified in `@Component()`, it also creates a new _child injector_ for that instance.
@ -278,7 +278,7 @@ Similarly, when a new NgModule is lazy-loaded at run time, Angular can create an
Angular DI 具有[分层注入体系](guide/hierarchical-dependency-injection),这意味着下级注入器也可以创建它们自己的服务实例。
Angular 会有规律的创建下级注入器。每当 Angular 创建一个在 `@Component()` 中指定了 `providers` 的组件实例时,它也会为该实例创建一个新的*子注入器*。
类似的,当在运行期间加载一个新的 NgModule 时Angular 也可以为它创建一个拥有自己的提供的注入器。
类似的,当在运行期间加载一个新的 NgModule 时Angular 也可以为它创建一个拥有自己的提供的注入器。
Child modules and component injectors are independent of each other, and create their own separate instances of the provided services. When Angular destroys an NgModule or component instance, it also destroys that injector and that injector's service instances.
@ -395,8 +395,8 @@ When you configure an injector with a provider, you associate that provider with
The injector maintains an internal *token-provider* map that it references when
asked for a dependency. The token is the key to the map.
当使用提供商配置注入器时,就会把提供商和一个 [DI 令牌](guide/glossary#di-token)关联起来。
注入器维护一个内部*令牌-提供*的映射表,当请求一个依赖项时就会引用它。令牌就是这个映射表的键。
当使用提供者配置注入器时,就会把提供者和一个 [DI 令牌](guide/glossary#di-token)关联起来。
注入器维护一个内部*令牌-提供*的映射表,当请求一个依赖项时就会引用它。令牌就是这个映射表的键。
In simple examples, the dependency value is an *instance*, and
the class *type* serves as its own lookup key.
@ -419,11 +419,11 @@ Angular knows to inject the service associated with that `HeroService` class tok
Many dependency values are provided by classes, but not all. The expanded *provide* object lets you associate different kinds of providers with a DI token.
很多依赖项的值都是通过类来提供的,但不是全部。扩展的 *provide* 对象让你可以把多种不同种类的提供和 DI 令牌关联起来。
很多依赖项的值都是通过类来提供的,但不是全部。扩展的 *provide* 对象让你可以把多种不同种类的提供和 DI 令牌关联起来。
* Learn more about [different kinds of providers](guide/dependency-injection-providers).
欲知详情,参见[不同种类的提供](guide/dependency-injection-providers)。
欲知详情,参见[不同种类的提供](guide/dependency-injection-providers)。
{@a optional}
@ -452,7 +452,7 @@ When using `@Optional()`, your code must be prepared for a null value. If you
don't register a logger provider anywhere, the injector sets the
value of `logger` to null.
当使用 `@Optional()` 时,你的代码必须能正确处理 null 值。如果你没有在任何地方注册过 logger 提供,那么注入器就会把 `logger` 的值设置为 null。
当使用 `@Optional()` 时,你的代码必须能正确处理 null 值。如果你没有在任何地方注册过 logger 提供,那么注入器就会把 `logger` 的值设置为 null。
<div class="alert is-helpful">
@ -476,7 +476,7 @@ and you know how to ask for an injected object (such as a service) by
adding a parameter to a constructor.
本页中你学到了 Angular 依赖注入的基础知识。
你可以注册多种提供,并且知道了如何通过为构造函数添加参数来请求所注入的对象(比如服务)。
你可以注册多种提供,并且知道了如何通过为构造函数添加参数来请求所注入的对象(比如服务)。
Dive deeper into the capabilities and advanced feature of the Angular DI system in the following pages:
@ -489,7 +489,7 @@ Dive deeper into the capabilities and advanced feature of the Angular DI system
* Learn more about [DI tokens and providers](guide/dependency-injection-providers).
到 [DI 令牌与提供](guide/dependency-injection-providers)中学习更多知识。
到 [DI 令牌与提供](guide/dependency-injection-providers)中学习更多知识。
* [Dependency Injection in Action](guide/dependency-injection-in-action) is a cookbook for some of the interesting things you can do with DI.

View File

@ -619,7 +619,7 @@ This type represents an `NgModule` along with additional providers.
Angular version 9 deprecates use of `ModuleWithProviders` without an explicitly generic type, where the generic type refers to the type of the `NgModule`.
In a future version of Angular, the generic will no longer be optional.
一些 Angular 库,例如 `@angular/router``@ngrx/store`,实现了一种返回 `ModuleWithProviders` 类型的 API通常借助名为 `forRoot()` 的方法)。此类型表示 `NgModule` 以及其它服务提供。 Angular 版本 9 不建议使用不带显式泛型类型的 `ModuleWithProviders`,泛型类型是指 `NgModule` 的类型。在 Angular 的未来版本中,泛型将不再是可选的。
一些 Angular 库,例如 `@angular/router``@ngrx/store`,实现了一种返回 `ModuleWithProviders` 类型的 API通常借助名为 `forRoot()` 的方法)。此类型表示 `NgModule` 以及其它服务提供。 Angular 版本 9 不建议使用不带显式泛型类型的 `ModuleWithProviders`,泛型类型是指 `NgModule` 的类型。在 Angular 的未来版本中,泛型将不再是可选的。
If you're using the CLI, `ng update` should [migrate your code automatically](guide/migration-module-with-providers).

View File

@ -166,7 +166,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [NgModules FAQ](guide/ngmodule-faq).

View File

@ -115,7 +115,7 @@ To incorporate the feature module into your app, you have to let the root module
Now the `AppModule` knows about the feature module. If you were to add any service providers to the feature module, `AppModule` would know about those too, as would any other feature modules. However, NgModules dont expose their components.
现在 `AppModule` 知道这个特性模块了。如果你往该特性模块中加入过任何服务提供`AppModule` 也同样会知道它其它模块中也一样。不过NgModule 并不会暴露出它们的组件。
现在 `AppModule` 知道这个特性模块了。如果你往该特性模块中加入过任何服务提供`AppModule` 也同样会知道它其它模块中也一样。不过NgModule 并不会暴露出它们的组件。
## Rendering a feature modules component template
@ -164,7 +164,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -250,7 +250,7 @@ The corresponding `ForbiddenValidatorDirective` serves as a wrapper around the `
Angular recognizes the directive's role in the validation process because the directive registers itself
with the `NG_VALIDATORS` provider, a provider with an extensible collection of validators.
Angular 在验证过程中能识别出指令的作用,是因为指令把自己注册成了 `NG_VALIDATORS` 提供商,该提供商拥有一组可扩展的验证器。
Angular 在验证过程中能识别出指令的作用,是因为指令把自己注册成了 `NG_VALIDATORS` 提供者,该提供者拥有一组可扩展的验证器。
<code-example path="form-validation/src/app/shared/forbidden-name.directive.ts" region="directive-providers" header="shared/forbidden-name.directive.ts (providers)"></code-example>

View File

@ -230,7 +230,7 @@ are for the whole app so it should only be in the root module,
not in feature modules. Feature modules only need the common
directives in `CommonModule`; they dont need to re-install app-wide providers.
对于运行在浏览器中的应用来说,都必须在根模块中 `AppModule` 导入 `BrowserModule` ,因为它提供了启动和运行浏览器应用时某些必须的服务。`BrowserModule` 的提供是面向整个应用的,所以它只能在根模块中使用,而不是特性模块。
对于运行在浏览器中的应用来说,都必须在根模块中 `AppModule` 导入 `BrowserModule` ,因为它提供了启动和运行浏览器应用时某些必须的服务。`BrowserModule` 的提供是面向整个应用的,所以它只能在根模块中使用,而不是特性模块。
特性模块只需要 `CommonModule` 中的常用指令,它们不需要重新安装所有全应用级的服务。
If you do import `BrowserModule` into a lazy loaded feature module,

View File

@ -151,7 +151,7 @@ which coordinates DOM object properties with data object properties.
Sometimes refers to a [dependency-injection](#dependency-injection) binding
between a [token](#token) and a dependency [provider](#provider).
有时也会指在“[令牌Token](#token)”和依赖[提供Provider](#provider)
有时也会指在“[令牌Token](#token)”和依赖[提供Provider](#provider)
之间的[依赖注入](#dependency-injection) 绑定。
{@a bootstrap}
@ -531,7 +531,7 @@ A design pattern and mechanism for creating and delivering some parts of an appl
In Angular, dependencies are typically services, but they also can be values, such as strings or functions.
An [injector](#injector) for an app (created automatically during bootstrap) instantiates dependencies when needed, using a configured [provider](#provider) of the service or value.
在 Angular 中,依赖通常是服务,但是也可以是值,比如字符串或函数。应用的[注入器](#injector)(它是在启动期间自动创建的)会使用该服务或值的配置好的[提供商](#provider)来按需实例化这些依赖。各个不同的提供商可以为同一个服务提供不同的实现。
在 Angular 中,依赖通常是服务,但是也可以是值,比如字符串或函数。应用的[注入器](#injector)(它是在启动期间自动创建的)会使用该服务或值的配置好的[提供者](#provider)来按需实例化这些依赖。各个不同的提供者可以为同一个服务提供不同的实现。
Learn more in [Dependency Injection in Angular](guide/dependency-injection).
@ -545,7 +545,7 @@ Learn more in [Dependency Injection in Angular](guide/dependency-injection).
A lookup token associated with a dependency [provider](#provider), for use with the [dependency injection](#di) system.
一种用来查阅的令牌,它关联到一个依赖[提供](#provider),用于[依赖注入](#di)系统中。
一种用来查阅的令牌,它关联到一个依赖[提供](#provider),用于[依赖注入](#di)系统中。
{@a differential-loading}
## differential loading
@ -784,7 +784,7 @@ using a configured [provider](#provider).
Injectors are created for NgModules automatically as part of the bootstrap process
and are inherited through the component hierarchy.
Angular [依赖注入系统](#dependency-injection)中可以在缓存中根据名字查找依赖,也可以通过配置过的[提供](#provider)来创建依赖。
Angular [依赖注入系统](#dependency-injection)中可以在缓存中根据名字查找依赖,也可以通过配置过的[提供](#provider)来创建依赖。
启动过程中会自动为每个模块创建一个注入器,并被组件树继承。
@ -798,7 +798,7 @@ Angular [依赖注入系统](#dependency-injection)中可以在缓存中根据
* You can configure injectors with different providers that can provide different implementations of the same dependency.
你可以为同一个依赖使用不同的提供商来配置这些注入器,这些提供商可以为同一个依赖提供不同的实现。
你可以为同一个依赖使用不同的提供者来配置这些注入器,这些提供者可以为同一个依赖提供不同的实现。
Learn more about the injector hierarchy in [Hierarchical Dependency Injectors](guide/hierarchical-dependency-injection).
@ -1202,19 +1202,19 @@ The [`angular.json`](guide/workspace-config) file configures all projects in a [
## provider
## 提供 (provider)
## 提供 (provider)
An object that implements one of the [`Provider`](api/core/Provider) interfaces. A provider object defines how to obtain an injectable dependency associated with a [DI token](#token).
An [injector](#injector) uses the provider to create a new instance of a dependency
for a class that requires it.
一个实现了 [`Provider`](api/core/Provider) 接口的对象。一个提供对象定义了如何获取与 [DI 令牌token](#token) 相关联的可注入依赖。
[注入器](#injector)会使用这个提供来创建它所依赖的那些类的实例。
一个实现了 [`Provider`](api/core/Provider) 接口的对象。一个提供对象定义了如何获取与 [DI 令牌token](#token) 相关联的可注入依赖。
[注入器](#injector)会使用这个提供来创建它所依赖的那些类的实例。
Angular registers its own providers with every injector, for services that Angular defines.
You can register your own providers for services that your app needs.
Angular 会为每个注入器注册一些 Angular 自己的服务。你也可以注册应用自己所需的服务提供
Angular 会为每个注入器注册一些 Angular 自己的服务。你也可以注册应用自己所需的服务提供
See also [service](#service), [dependency injection](#di).
@ -1281,7 +1281,7 @@ A tool that configures and implements navigation among states and [views](#view)
The `Router` module is an [NgModule](#ngmodule) that provides the necessary service providers and directives for navigating through application views. A [routing component](#routing-component) is one that imports the `Router` module and whose template contains a `RouterOutlet` element where it can display views produced by the router.
`Router` 模块是一个 [NgModule](#ngmodule),它提供在应用视图间导航时需要的服务提供和指令。[路由组件](#routing-component)是一种组件,它导入了 `Router` 模块,并且其模板中包含 `RouterOutlet` 元素,路由器生成的视图就会被显示在那里。
`Router` 模块是一个 [NgModule](#ngmodule),它提供在应用视图间导航时需要的服务提供和指令。[路由组件](#routing-component)是一种组件,它导入了 `Router` 模块,并且其模板中包含 `RouterOutlet` 元素,路由器生成的视图就会被显示在那里。
The router defines navigation among views on a single page, as opposed to navigation among pages. It interprets URL-like links to determine which views to create or destroy, and which components to load or unload. It allows you to take advantage of [lazy loading](#lazy-load) in your Angular apps.
@ -1430,8 +1430,8 @@ The `@Injectable()` metadata allows the service class to be used with the [depen
The injectable class is instantiated by a [provider](#provider).
[Injectors](#injector) maintain lists of providers and use them to provide service instances when they are required by components or other services.
`@Injectable` 元数据让服务类能用于[依赖注入](#di)机制中。可注入的类是用[提供](#provider)进行实例化的。
[各个注入器](#injector)会维护一个提供的列表,并根据组件或其它服务的需要,用它们来提供服务的实例。
`@Injectable` 元数据让服务类能用于[依赖注入](#di)机制中。可注入的类是用[提供](#provider)进行实例化的。
[各个注入器](#injector)会维护一个提供的列表,并根据组件或其它服务的需要,用它们来提供服务的实例。
To learn more, see [Introduction to Services and Dependency Injection](guide/architecture-services).
@ -1592,7 +1592,7 @@ Read about how to write template expressions in [Template expressions](guide/te
An opaque identifier used for efficient table lookup. In Angular, a [DI token](#di-token) is used to find [providers](#provider) of dependencies in the [dependency injection](#di) system.
用于高效查表的不透明标识符(译注:不透明是指你不必了解其细节)。在 Angular 中,[DI 令牌](#di-token)用于在[依赖注入](#di)系统中查找[服务提供](#provider)。
用于高效查表的不透明标识符(译注:不透明是指你不必了解其细节)。在 Angular 中,[DI 令牌](#di-token)用于在[依赖注入](#di)系统中查找[服务提供](#provider)。
{@a transpile}

View File

@ -8,7 +8,7 @@ achieve the desired visibility of injectables in your apps.
By understanding these rules, you can determine in which
NgModule, Component or Directive you should declare a provider.
Angular 中的注入器有一些规则,您可以利用这些规则来在应用程序中获得所需的可注入对象可见性。通过了解这些规则,可以确定应在哪个 NgModule、组件或指令中声明服务提供
Angular 中的注入器有一些规则,您可以利用这些规则来在应用程序中获得所需的可注入对象可见性。通过了解这些规则,可以确定应在哪个 NgModule、组件或指令中声明服务提供
## Two injector hierarchies
@ -75,7 +75,7 @@ a need to inject it. Read more
about [tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers)
in [DI Providers](guide/dependency-injection-providers).
摇树优化对于库特别有用,因为使用该库的应用程序不需要注入它。在 [DI 提供商中](guide/dependency-injection-providers)了解有关[可摇树优化的提供商](guide/dependency-injection-providers#tree-shakable-providers)的更多信息。
摇树优化对于库特别有用,因为使用该库的应用程序不需要注入它。在 [DI 提供者中](guide/dependency-injection-providers)了解有关[可摇树优化的提供者](guide/dependency-injection-providers#tree-shakable-providers)的更多信息。
</div>
@ -155,7 +155,7 @@ many apps you have running.
You can configure additional platform-specific providers at the
platform level by supplying `extraProviders` using the `platformBrowser()` function.
`platformBrowserDynamic()` 方法创建一个由 `PlatformModule` 配置的注入器,该注入器包含特定平台的依赖项。这允许多个应用共享同一套平台配置。例如,无论您运行多少个应用程序,浏览器都只有一个 URL 栏。您可以使用 `platformBrowser()` 函数提供 `extraProviders`,从而在平台级别配置特定平台的额外提供
`platformBrowserDynamic()` 方法创建一个由 `PlatformModule` 配置的注入器,该注入器包含特定平台的依赖项。这允许多个应用共享同一套平台配置。例如,无论您运行多少个应用程序,浏览器都只有一个 URL 栏。您可以使用 `platformBrowser()` 函数提供 `extraProviders`,从而在平台级别配置特定平台的额外提供
The next parent injector in the hierarchy is the `NullInjector()`,
@ -194,7 +194,7 @@ All requests forward up to the root injector, whether you configured it
with the `bootstrapModule()` method, or registered all providers
with `root` in their own services.
无论是使用 `bootstrapModule()` 的方法配置它,还是将所有提供都用 `root` 注册到其自己的服务中,所有请求最终都会转发到 `root` 注入器。
无论是使用 `bootstrapModule()` 的方法配置它,还是将所有提供都用 `root` 注册到其自己的服务中,所有请求最终都会转发到 `root` 注入器。
<div class="alert is-helpful">
@ -206,7 +206,7 @@ If you configure an app-wide provider in the `@NgModule()` of
`@Injectable()` metadata. You can do this to configure a
non-default provider of a service that is shared with multiple apps.
如果你在 `AppModule``@NgModule()` 中配置应用级提供商,它就会覆盖一个在 `@Injectable()``root` 元数据中配置的提供商。您可以用这种方式,来配置供多个应用共享的服务的非默认提供商
如果你在 `AppModule``@NgModule()` 中配置应用级提供者,它就会覆盖一个在 `@Injectable()``root` 元数据中配置的提供者。您可以用这种方式,来配置供多个应用共享的服务的非默认提供者
Here is an example of the case where the component router
@ -215,7 +215,7 @@ a non-default [location strategy](guide/router#location-strategy)
by listing its provider
in the `providers` list of the `AppModule`.
下面的例子中,通过把 [location 策略](guide/router#location-strategy) 的提供添加到 `AppModule``providers` 列表中,为路由器配置了非默认的 [location 策略](guide/router#location-strategy)。
下面的例子中,通过把 [location 策略](guide/router#location-strategy) 的提供添加到 `AppModule``providers` 列表中,为路由器配置了非默认的 [location 策略](guide/router#location-strategy)。
<code-example path="dependency-injection-in-action/src/app/app.module.ts" region="providers" header="src/app/app.module.ts (providers)">
@ -290,7 +290,7 @@ directive.
Components and directives on the same element share an injector.
组件是一种特殊类型的指令,这意味着 `@Directive()` 具有 `providers` 属性,`@Component()` 也同样如此。
这意味着指令和组件都可以使用 `providers` 属性来配置提供商。当使用 `providers` 属性为组件或指令配置提供商时,该提供程商就属于该组件或指令的 `ElementInjector`。同一元素上的组件和指令共享同一个注入器。
这意味着指令和组件都可以使用 `providers` 属性来配置提供者。当使用 `providers` 属性为组件或指令配置提供者时,该提供程商就属于该组件或指令的 `ElementInjector`。同一元素上的组件和指令共享同一个注入器。
{@a resolution-rules}
@ -322,7 +322,7 @@ If the component's injector lacks the provider, it passes the request
up to its parent component's `ElementInjector`.
当组件声明依赖项时Angular 会尝试使用它自己的 `ElementInjector` 来满足该依赖。
如果组件的注入器缺少提供,它将把请求传给其父组件的 `ElementInjector`
如果组件的注入器缺少提供,它将把请求传给其父组件的 `ElementInjector`
The requests keep forwarding up until Angular finds an injector that can
@ -336,7 +336,7 @@ it goes back to the element where the request originated and looks
in the `ModuleInjector` hierarchy.
If Angular still doesn't find the provider, it throws an error.
如果 Angular 在任何 `ElementInjector` 中都找不到提供,它将返回到发起请求的元素,并在 `ModuleInjector` 层次结构中进行查找。如果 Angular 仍然找不到提供,它将引发错误。
如果 Angular 在任何 `ElementInjector` 中都找不到提供,它将返回到发起请求的元素,并在 `ModuleInjector` 层次结构中进行查找。如果 Angular 仍然找不到提供,它将引发错误。
If you have registered a provider for the same DI token at
@ -345,7 +345,7 @@ it uses to resolve the dependency. If, for example, a provider
is registered locally in the component that needs a service,
Angular doesn't look for another provider of the same service.
如果您已在不同级别注册了相同 DI 令牌的提供商,则 Angular 会用遇到的第一个来解析该依赖。例如,如果提供商已经在需要此服务的组件中本地注册了,则 Angular 不会再寻找同一服务的其他提供
如果您已在不同级别注册了相同 DI 令牌的提供者,则 Angular 会用遇到的第一个来解析该依赖。例如,如果提供者已经在需要此服务的组件中本地注册了,则 Angular 不会再寻找同一服务的其他提供
## Resolution modifiers
@ -453,14 +453,14 @@ with `@Self()` and `@Optional()` will return `null` because
`@Self()` tells the injector to stop searching in the current
host element.
在这个例子中,有一个父提供,注入服务将返回该值,但是,使用 `@Self()``@Optional()` 注入的服务将返回 `null` 因为 `@Self()` 告诉注入器在当前宿主元素上就要停止搜索。
在这个例子中,有一个父提供,注入服务将返回该值,但是,使用 `@Self()``@Optional()` 注入的服务将返回 `null` 因为 `@Self()` 告诉注入器在当前宿主元素上就要停止搜索。
Another example shows the component class with a provider
for `FlowerService`. In this case, the injector looks no further
than the current `ElementInjector` because it finds the `FlowerService` and returns the yellow flower 🌼.
另一个示例显示了具有 `FlowerService` 提供的组件类。在这个例子中,注入器没有超出当前 `ElementInjector` 就停止了,因为它已经找到了 `FlowerService` 并返回了黄色花朵🌼。
另一个示例显示了具有 `FlowerService` 提供的组件类。在这个例子中,注入器没有超出当前 `ElementInjector` 就停止了,因为它已经找到了 `FlowerService` 并返回了黄色花朵🌼。
<code-example path="resolution-modifiers/src/app/self/self.component.ts" header="resolution-modifiers/src/app/self/self.component.ts" region="self-component">
@ -519,7 +519,7 @@ class Person {
`@Host()` lets you designate a component as the last stop in the injector tree when searching for providers. Even if there is a service instance further up the tree, Angular won't continue looking. Use `@Host()` as follows:
`@Host()` 使您可以在搜索提供时将当前组件指定为注入器树的最后一站。即使树的更上级有一个服务实例Angular 也不会继续寻找。使用 `@Host()` 的例子如下:
`@Host()` 使您可以在搜索提供时将当前组件指定为注入器树的最后一站。即使树的更上级有一个服务实例Angular 也不会继续寻找。使用 `@Host()` 的例子如下:
<code-example path="resolution-modifiers/src/app/host/host.component.ts" header="resolution-modifiers/src/app/host/host.component.ts" region="host-component">
@ -677,7 +677,7 @@ this location in the logical tree its value would be `Value`.
- `@Provide(Token=Value)` demonstrates that there is a declaration of
`Token` provider with value `Value` at this location in the logical tree.
`@Provide(Token=Value)` 表示,在逻辑树中的此位置存在一个值为 `Value``Token` 提供的声明。
`@Provide(Token=Value)` 表示,在逻辑树中的此位置存在一个值为 `Value``Token` 提供的声明。
- `@NgModule(Token)` demonstrates that a fallback `NgModule` injector
@ -856,7 +856,7 @@ injection token can't be found in the `ElementInjector`s.
Now, in the `ChildComponent` class, add a provider for `FlowerService`
to demonstrate more complex resolution rules in the upcoming sections:
现在,在 `ChildComponent` 类中,为 `FlowerService` 添加一个提供,以便在接下来的小节中演示更复杂的解析规则:
现在,在 `ChildComponent` 类中,为 `FlowerService` 添加一个提供,以便在接下来的小节中演示更复杂的解析规则:
<code-example path="providers-viewproviders/src/app/child/child.component.1.ts" header="providers-viewproviders/src/app/child.component.ts" region="flowerservice">
@ -1235,7 +1235,7 @@ ending `ElementInjector` using the visibility decorators `@Host()`,
### Visibility of provided tokens
### 提供令牌的可见性
### 提供令牌的可见性
Visibility decorators influence where the search for the injection
@ -1572,7 +1572,7 @@ The ability to configure one or more providers at different levels
opens up useful possibilities.
For a look at the following scenarios in a working app, see the <live-example>heroes use case examples</live-example>.
在不同级别配置一个或多个提供的能力开辟了很有用的可能性。要查看正在运行的应用中的以下情况,请参阅<live-example>英雄示例</live-example>
在不同级别配置一个或多个提供的能力开辟了很有用的可能性。要查看正在运行的应用中的以下情况,请参阅<live-example>英雄示例</live-example>
### Scenario: service isolation
@ -1718,7 +1718,7 @@ The `HeroTaxReturnComponent` has its own provider of the `HeroTaxReturnService`.
Recall that every component _instance_ has its own injector.
Providing the service at the component level ensures that _every_ instance of the component gets its own, private instance of the service, and no tax return gets overwritten.
`HeroTaxReturnComponent` 有它自己的 `HeroTaxReturnService` 提供
`HeroTaxReturnComponent` 有它自己的 `HeroTaxReturnService` 提供
回忆一下,每个组件的*实例*都有它自己的注入器。
在组件级提供服务可以确保组件的*每个*实例都得到一个自己的、私有的服务实例,而报税单也不会再被意外覆盖了。
@ -1734,7 +1734,7 @@ You can review it and download it from the <live-example></live-example>.
### Scenario: specialized providers
### 场景:专门的提供
### 场景:专门的提供
Another reason to re-provide a service at another level is to substitute a _more specialized_ implementation of that service, deeper in the component tree.
@ -1745,7 +1745,7 @@ Suppose you configured the root injector (marked as A) with _generic_ providers
`CarService`, `EngineService` and `TiresService`.
考虑一个依赖于一系列服务的 Car 组件。
假设你在根注入器(代号 A中配置了*通用的*提供`CarService`、`EngineService` 和 `TiresService`
假设你在根注入器(代号 A中配置了*通用的*提供`CarService`、`EngineService` 和 `TiresService`
You create a car component (A) that displays a car constructed from these three generic services.
@ -1754,11 +1754,11 @@ You create a car component (A) that displays a car constructed from these three
Then you create a child component (B) that defines its own, _specialized_ providers for `CarService` and `EngineService`
that have special capabilities suitable for whatever is going on in component (B).
然后你创建一个子组件B它为 `CarService``EngineService` 定义了自己*特有的*提供,它们具有适用于组件 B 的特有能力。
然后你创建一个子组件B它为 `CarService``EngineService` 定义了自己*特有的*提供,它们具有适用于组件 B 的特有能力。
Component (B) is the parent of another component (C) that defines its own, even _more specialized_ provider for `CarService`.
组件 B 是另一个组件 C 的父组件,而组件 C 又定义了自己的,*更特殊的*`CarService` 提供
组件 B 是另一个组件 C 的父组件,而组件 C 又定义了自己的,*更特殊的*`CarService` 提供
<div class="lightbox">
@ -1768,7 +1768,7 @@ Component (B) is the parent of another component (C) that defines its own, even
Behind the scenes, each component sets up its own injector with zero, one, or more providers defined for that component itself.
在幕后,每个组件都有自己的注入器,这个注入器带有为组件本身准备的 0 个、1 个或多个提供
在幕后,每个组件都有自己的注入器,这个注入器带有为组件本身准备的 0 个、1 个或多个提供
When you resolve an instance of `Car` at the deepest component (C),
its injector produces an instance of `Car` resolved by injector (C) with an `Engine` resolved by injector (B) and
@ -1790,4 +1790,4 @@ its injector produces an instance of `Car` resolved by injector (C) with an `Eng
For more information on Angular dependency injection, see the [DI Providers](guide/dependency-injection-providers) and [DI in Action](guide/dependency-injection-in-action) guides.
要了解关于 Angular 依赖注入的更多信息,参见 [DI 提供](guide/dependency-injection-providers)和 [DI 实战](guide/dependency-injection-in-action) 两章。
要了解关于 Angular 依赖注入的更多信息,参见 [DI 提供](guide/dependency-injection-providers)和 [DI 实战](guide/dependency-injection-in-action) 两章。

View File

@ -829,7 +829,7 @@ You should provide interceptors in `AppModule` as well.
After importing the `HTTP_INTERCEPTORS` injection token from `@angular/common/http`,
write the `NoopInterceptor` provider like this:
在从 `@angular/common/http` 中导入了 `HTTP_INTERCEPTORS` 注入令牌之后,编写如下的 `NoopInterceptor` 提供注册语句:
在从 `@angular/common/http` 中导入了 `HTTP_INTERCEPTORS` 注入令牌之后,编写如下的 `NoopInterceptor` 提供注册语句:
<code-example
path="http/src/app/http-interceptors/index.ts"
@ -841,7 +841,7 @@ This required setting tells Angular that `HTTP_INTERCEPTORS` is a token for a _m
that injects an array of values, rather than a single value.
注意 `multi: true` 选项。
这个必须的选项会告诉 Angular `HTTP_INTERCEPTORS` 是一个*多重提供*的令牌,表示它会注入一个多值的数组,而不是单一的值。
这个必须的选项会告诉 Angular `HTTP_INTERCEPTORS` 是一个*多重提供*的令牌,表示它会注入一个多值的数组,而不是单一的值。
You _could_ add this provider directly to the providers array of the `AppModule`.
However, it's rather verbose and there's a good chance that
@ -849,7 +849,7 @@ you'll create more interceptors and provide them in the same way.
You must also pay [close attention to the order](#interceptor-order)
in which you provide these interceptors.
你*也可以*直接把这个提供商添加到 `AppModule` 中的提供商数组中,不过那样会非常啰嗦。况且,你将来还会用这种方式创建更多的拦截器并提供它们。
你*也可以*直接把这个提供者添加到 `AppModule` 中的提供者数组中,不过那样会非常啰嗦。况且,你将来还会用这种方式创建更多的拦截器并提供它们。
你还要[特别注意提供这些拦截器的顺序](#interceptor-order)。
Consider creating a "barrel" file that gathers all the interceptor providers into an `httpInterceptorProviders` array, starting with this first one, the `NoopInterceptor`.

View File

@ -299,7 +299,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -80,7 +80,7 @@ typical characteristics, in real world apps, you may see hybrids.
Domain feature modules rarely have providers. When they do, the lifetime of the provided services should be the same as the lifetime of the module.
领域特性模块很少会有服务提供。如果有,那么这些服务的生命周期必须和该模块的生命周期完全相同。
领域特性模块很少会有服务提供。如果有,那么这些服务的生命周期必须和该模块的生命周期完全相同。
Domain feature modules are typically imported exactly once by a larger feature module.
@ -125,7 +125,7 @@ typical characteristics, in real world apps, you may see hybrids.
Routed feature modules rarely have providers for reasons explained in [Lazy Loading Feature Modules](/guide/lazy-loading-ngmodules). When they do, the lifetime of the provided services should be the same as the lifetime of the module. Don't provide application-wide singleton services in a routed feature module or in a module that the routed module imports.
路由特性模块很少会有服务提供,原因参见[惰性加载的特性模块](/guide/lazy-loading-ngmodules)中的解释。如果那样做,那么它所提供的服务的生命周期必须与该模块的生命周期完全相同。不要在路由特性模块或被路由特性模块所导入的模块中提供全应用级的单例服务。
路由特性模块很少会有服务提供,原因参见[惰性加载的特性模块](/guide/lazy-loading-ngmodules)中的解释。如果那样做,那么它所提供的服务的生命周期必须与该模块的生命周期完全相同。不要在路由特性模块或被路由特性模块所导入的模块中提供全应用级的单例服务。
</td>
@ -173,7 +173,7 @@ typical characteristics, in real world apps, you may see hybrids.
Adds guard and resolver service providers to the module's providers.
把路由守卫和解析器的服务提供添加到该模块的 `providers` 中。
把路由守卫和解析器的服务提供添加到该模块的 `providers` 中。
</li>
@ -227,7 +227,7 @@ typical characteristics, in real world apps, you may see hybrids.
Service modules provide utility services such as data access and messaging. Ideally, they consist entirely of providers and have no declarations. Angular's `HttpClientModule` is a good example of a service module.
服务模块提供了一些工具服务,比如数据访问和消息。理论上,它们应该是完全由服务提供组成的不应该有可声明对象。Angular 的 `HttpClientModule` 就是一个服务模块的好例子。
服务模块提供了一些工具服务,比如数据访问和消息。理论上,它们应该是完全由服务提供组成的不应该有可声明对象。Angular 的 `HttpClientModule` 就是一个服务模块的好例子。
The root `AppModule` is the only module that should import service modules.
@ -259,7 +259,7 @@ typical characteristics, in real world apps, you may see hybrids.
A widget module should rarely have providers.
窗口部件模块很少会有服务提供
窗口部件模块很少会有服务提供
Import widget modules in any module whose component templates need the widgets.
@ -298,7 +298,7 @@ The following table summarizes the key characteristics of each feature module gr
Providers
提供 `providers`
提供 `providers`
</th>
@ -553,4 +553,4 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。

View File

@ -146,12 +146,12 @@ The following table summarizes the `@NgModule` metadata properties.
A list of dependency-injection providers.
依赖注入提供的列表。
依赖注入提供的列表。
Angular registers these providers with the NgModule's injector.
If it is the NgModule used for bootstrapping then it is the root injector.
Angular 会使用该模块的注入器注册这些提供
Angular 会使用该模块的注入器注册这些提供
如果该模块是启动模块,那就会使用根注入器。
These services become available for injection into any component, directive, pipe or service which is a child of this injector.
@ -177,7 +177,7 @@ The following table summarizes the `@NgModule` metadata properties.
For more information on injector hierarchy and scoping, see [Providers](guide/providers) and the [DI Guide](guide/dependency-injection).
要深入了解关于多级注入器及其作用域,参见[服务提供](guide/providers)。
要深入了解关于多级注入器及其作用域,参见[服务提供](guide/providers)。
</td>
@ -380,7 +380,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -173,7 +173,7 @@ should import `BrowserModule` from `@angular/platform-browser`.
`BrowserModule` provides services that are essential to launch and run a browser app.
`BrowserModule` 提供了启动和运行浏览器应用的那些基本的服务提供
`BrowserModule` 提供了启动和运行浏览器应用的那些基本的服务提供
`BrowserModule` also re-exports `CommonModule` from `@angular/common`,
which means that components in the `AppModule` module also have access to
@ -187,7 +187,7 @@ They need the common directives. They don't need to re-install the app-wide prov
在其它任何模块中都*不要导入*`BrowserModule`。
*特性模块*和*惰性加载模块*应该改成导入 `CommonModule`
它们需要通用的指令。它们不需要重新初始化全应用级的提供
它们需要通用的指令。它们不需要重新初始化全应用级的提供
Importing `CommonModule` also frees feature modules for use on _any_ target platform, not just browsers.
@ -278,7 +278,7 @@ Its only purpose is to add http service providers to the application as a whole.
纯服务模块没有公开(导出)的声明。
例如,没必要重新导出 `HttpClientModule`,因为它不导出任何东西。
它唯一的用途是一起把 http 的那些服务提供添加到应用中。
它唯一的用途是一起把 http 的那些服务提供添加到应用中。
<hr/>
@ -319,7 +319,7 @@ Its only purpose is to add http service providers to the application as a whole.
不要费心去导出纯服务类。
纯服务类的模块不会导出任何可供其它模块使用的[可声明类](guide/ngmodule-faq#q-declarable)。
例如,不用重新导出 `HttpClientModule`,因为它没有导出任何东西。
它唯一的用途是把那些 http 服务提供一起添加到应用中。
它唯一的用途是把那些 http 服务提供一起添加到应用中。
<hr/>
@ -329,7 +329,7 @@ Its only purpose is to add http service providers to the application as a whole.
The `forRoot()` static method is a convention that makes it easy for developers to configure services and providers that are intended to be singletons. A good example of `forRoot()` is the `RouterModule.forRoot()` method.
静态方法 `forRoot()` 是一个约定,它可以让开发人员更轻松的配置模块的想要单例使用的服务及其提供。`RouterModule.forRoot()` 就是一个很好的例子。
静态方法 `forRoot()` 是一个约定,它可以让开发人员更轻松的配置模块的想要单例使用的服务及其提供。`RouterModule.forRoot()` 就是一个很好的例子。
Apps pass a `Routes` object to `RouterModule.forRoot()` in order to configure the app-wide `Router` service with routes.
`RouterModule.forRoot()` returns a [ModuleWithProviders](api/core/ModuleWithProviders).
@ -363,29 +363,29 @@ configure services in root and feature modules respectively.
Follow this convention when you write similar modules with configurable service providers.
当你写类似的需要可配置的服务提供时,请遵循这个约定。
当你写类似的需要可配置的服务提供时,请遵循这个约定。
<hr/>
## Why is a service provided in a feature module visible everywhere?
## 为什么服务提供在特性模块中的任何地方都是可见的?
## 为什么服务提供在特性模块中的任何地方都是可见的?
Providers listed in the `@NgModule.providers` of a bootstrapped module have application scope.
Adding a service provider to `@NgModule.providers` effectively publishes the service to the entire application.
列在引导模块的 `@NgModule.providers` 中的服务提供具有**全应用级作用域**。
`NgModule.providers` 中添加服务提供将导致该服务被发布到整个应用中。
列在引导模块的 `@NgModule.providers` 中的服务提供具有**全应用级作用域**。
`NgModule.providers` 中添加服务提供将导致该服务被发布到整个应用中。
When you import an NgModule,
Angular adds the module's service providers (the contents of its `providers` list)
to the application root injector.
当你导入一个模块时Angular 就会把该模块的服务提供(也就是它的 `providers` 列表中的内容)加入该应用的*根注入器*中。
当你导入一个模块时Angular 就会把该模块的服务提供(也就是它的 `providers` 列表中的内容)加入该应用的*根注入器*中。
This makes the provider visible to every class in the application that knows the provider's lookup token, or name.
这会让该提供商对应用中所有知道该提供商令牌token的类都可见。
这会让该提供者对应用中所有知道该提供者令牌token的类都可见。
Extensibility through NgModule imports is a primary goal of the NgModule system.
Merging NgModule providers into the application injector
@ -393,7 +393,7 @@ makes it easy for a module library to enrich the entire application with new ser
By adding the `HttpClientModule` once, every application component can make HTTP requests.
通过 NgModule 导入来实现可扩展性是 NgModule 体系的主要设计目标。
把 NgModule 的提供并入应用程序的注入器可以让库模块使用新的服务来强化应用程序变得更容易。
把 NgModule 的提供并入应用程序的注入器可以让库模块使用新的服务来强化应用程序变得更容易。
只要添加一次 `HttpClientModule`,那么应用中的每个组件就都可以发起 Http 请求了。
However, this might feel like an unwelcome surprise if you expect the module's services
@ -415,12 +415,12 @@ To limit access to a service, consider lazy loading the NgModule that provides t
## Why is a service provided in a lazy-loaded module visible only to that module?
## 为什么在惰性加载模块中声明的服务提供只对该模块自身可见?
## 为什么在惰性加载模块中声明的服务提供只对该模块自身可见?
Unlike providers of the modules loaded at launch,
providers of lazy-loaded modules are *module-scoped*.
和启动时就加载的模块中的提供商不同,惰性加载模块中的提供商是*局限于模块*的。
和启动时就加载的模块中的提供者不同,惰性加载模块中的提供者是*局限于模块*的。
When the Angular router lazy-loads a module, it creates a new execution context.
That [context has its own injector](guide/ngmodule-faq#q-why-child-injector "Why Angular creates a child injector"),
@ -431,13 +431,13 @@ which is a direct child of the application injector.
The router adds the lazy module's providers and the providers of its imported NgModules to this child injector.
路由器把该惰性加载模块的提供商和它导入的模块的提供商添加到这个子注入器中。
路由器把该惰性加载模块的提供者和它导入的模块的提供者添加到这个子注入器中。
These providers are insulated from changes to application providers with the same lookup token.
When the router creates a component within the lazy-loaded context,
Angular prefers service instances created from these providers to the service instances of the application root injector.
这些提供商不会被拥有相同令牌的应用级别提供商的变化所影响。
这些提供者不会被拥有相同令牌的应用级别提供者的变化所影响。
当路由器在惰性加载环境中创建组件时Angular 优先使用惰性加载模块中的服务实例,而不是来自应用的根注入器的。
<hr/>
@ -449,18 +449,18 @@ Angular prefers service instances created from these providers to the service in
When two imported modules, loaded at the same time, list a provider with the same token,
the second module's provider "wins". That's because both providers are added to the same injector.
当同时加载了两个导入的模块,它们都列出了使用同一个令牌的提供商时,后导入的模块会“获胜”,这是因为这两个提供商都被添加到了同一个注入器中。
当同时加载了两个导入的模块,它们都列出了使用同一个令牌的提供者时,后导入的模块会“获胜”,这是因为这两个提供者都被添加到了同一个注入器中。
When Angular looks to inject a service for that token,
it creates and delivers the instance created by the second provider.
当 Angular 尝试根据令牌注入服务时,它使用第二个提供来创建并交付服务实例。
当 Angular 尝试根据令牌注入服务时,它使用第二个提供来创建并交付服务实例。
_Every_ class that injects this service gets the instance created by the second provider.
Even classes declared within the first module get the instance created by the second provider.
*每个*注入了该服务的类获得的都是由第二个提供创建的实例。
即使是声明在第一个模块中的类,它取得的实例也是来自第二个提供的。
*每个*注入了该服务的类获得的都是由第二个提供创建的实例。
即使是声明在第一个模块中的类,它取得的实例也是来自第二个提供的。
If NgModule A provides a service for token 'X' and imports an NgModule B
that also provides a service for token 'X', then NgModule A's service definition "wins".
@ -490,13 +490,13 @@ that is, they are available for injection throughout the application.
Imported providers are easily replaced by providers from another imported NgModule.
Such replacement might be by design. It could be unintentional and have adverse consequences.
导入的提供商很容易被由其它导入模块中的提供商替换掉。
导入的提供者很容易被由其它导入模块中的提供者替换掉。
这虽然是故意这样设计的,但是也可能引起意料之外的结果。
As a general rule, import modules with providers _exactly once_, preferably in the application's _root module_.
That's also usually the best place to configure, wrap, and override them.
作为一个通用的规则,应该*只导入一次*带提供的模块,最好在应用的*根模块*中。
作为一个通用的规则,应该*只导入一次*带提供的模块,最好在应用的*根模块*中。
那里也是配置、包装和改写这些服务的最佳位置。
Suppose a module requires a customized `HttpBackend` that adds a special header for all Http requests.
@ -505,7 +505,7 @@ or merely imports the `HttpClientModule`, it could override this module's `HttpB
losing the special header. The server will reject http requests from this module.
假设模块需要一个定制过的 `HttpBackend`,它为所有的 Http 请求添加一个特别的请求头。
如果应用中其它地方的另一个模块也定制了 `HttpBackend` 或仅仅导入了 `HttpClientModule`,它就会改写当前模块的 `HttpBackend` 提供,丢掉了这个特别的请求头。
如果应用中其它地方的另一个模块也定制了 `HttpBackend` 或仅仅导入了 `HttpClientModule`,它就会改写当前模块的 `HttpBackend` 提供,丢掉了这个特别的请求头。
这样服务器就会拒绝来自该模块的请求。
To avoid this problem, import the `HttpClientModule` only in the `AppModule`, the application _root module_.
@ -514,7 +514,7 @@ To avoid this problem, import the `HttpClientModule` only in the `AppModule`, th
If you must guard against this kind of "provider corruption", *don't rely on a launch-time module's `providers`.*
如果你必须防范这种“提供腐化”现象,那就*不要依赖于“启动时加载”模块的 `providers`*。
如果你必须防范这种“提供腐化”现象,那就*不要依赖于“启动时加载”模块的 `providers`*。
Load the module lazily if you can.
Angular gives a [lazy-loaded module](guide/ngmodule-faq#q-lazy-loaded-module-provider-visibility) its own child injector.
@ -522,7 +522,7 @@ The module's providers are visible only within the component tree created with t
只要可能,就让模块惰性加载。
Angular 给了[惰性加载模块](guide/ngmodule-faq#q-lazy-loaded-module-provider-visibility)自己的子注入器。
该模块中的提供只对由该注入器创建的组件树可见。
该模块中的提供只对由该注入器创建的组件树可见。
If you must load the module eagerly, when the application starts,
*provide the service in a component instead.*
@ -539,7 +539,7 @@ Recall that Angular creates a child injector for each component instance and pop
with the component's own providers.
那就创建一个“顶层组件”来扮演该模块中所有组件的根。
把这个自定义的 `HttpBackend` 提供添加到这个顶层组件的 `providers` 列表中,而不是该模块的 `providers` 中。
把这个自定义的 `HttpBackend` 提供添加到这个顶层组件的 `providers` 列表中,而不是该模块的 `providers` 中。
回忆一下Angular 会为每个组件实例创建一个子注入器,并使用组件自己的 `providers` 来配置这个注入器。
When a child of this component asks for the `HttpBackend` service,
@ -571,16 +571,16 @@ Though you can limit access to a service by providing it in a lazy loaded module
## Should I add application-wide providers to the root `AppModule` or the root `AppComponent`?
## 我应该把全应用级提供添加到根模块 `AppModule` 中还是根组件 `AppComponent` 中?
## 我应该把全应用级提供添加到根模块 `AppModule` 中还是根组件 `AppComponent` 中?
Define application-wide providers by specifying `providedIn: 'root'` on its `@Injectable()` decorator (in the case of services) or at `InjectionToken` construction (in the case where tokens are provided). Providers that are created this way automatically are made available to the entire application and don't need to be listed in any module.
通过在服务的 `@Injectable()` 装饰器中(例如服务)指定 `providedIn: 'root'` 来定义全应用级提供,或者 `InjectionToken` 的构造器(例如提供令牌的地方),都可以定义全应用级提供
通过这种方式创建的服务提供会自动在整个应用中可用,而不用把它列在任何模块中。
通过在服务的 `@Injectable()` 装饰器中(例如服务)指定 `providedIn: 'root'` 来定义全应用级提供,或者 `InjectionToken` 的构造器(例如提供令牌的地方),都可以定义全应用级提供
通过这种方式创建的服务提供会自动在整个应用中可用,而不用把它列在任何模块中。
If a provider cannot be configured in this way (perhaps because it has no sensible default value), then register application-wide providers in the root `AppModule`, not in the `AppComponent`.
如果某个提供不能用这种方式配置(可能因为它没有有意义的默认值),那就在根模块 `AppModule` 中注册这些全应用级服务,而不是在 `AppComponent` 中。
如果某个提供不能用这种方式配置(可能因为它没有有意义的默认值),那就在根模块 `AppModule` 中注册这些全应用级服务,而不是在 `AppComponent` 中。
Lazy-loaded modules and their components can inject `AppModule` services;
they can't inject `AppComponent` services.
@ -595,7 +595,7 @@ from components outside the `AppComponent` tree. This is a rare use case.
More generally, [prefer registering providers in NgModules](guide/ngmodule-faq#q-component-or-module) to registering in components.
更一般地说,[优先把提供注册进模块中](guide/ngmodule-faq#q-component-or-module),而不是组件中。
更一般地说,[优先把提供注册进模块中](guide/ngmodule-faq#q-component-or-module),而不是组件中。
<h3 class="no-toc">Discussion</h3>
@ -605,8 +605,8 @@ Angular registers all startup module providers with the application root injecto
The services that root injector providers create have application scope, which
means they are available to the entire application.
Angular 把所有启动期模块的提供都注册进了应用的根注入器中。
这些服务是由根注入器中的提供创建的,并且在整个应用中都可用。
Angular 把所有启动期模块的提供都注册进了应用的根注入器中。
这些服务是由根注入器中的提供创建的,并且在整个应用中都可用。
它们具有*应用级作用域*。
Certain services, such as the `Router`, only work when you register them in the application root injector.
@ -617,7 +617,7 @@ By contrast, Angular registers `AppComponent` providers with the `AppComponent`'
`AppComponent` services are available only to that component and its component tree.
They have component scope.
相反Angular 使用 `AppComponent` 自己的注入器注册了 `AppComponent` 的提供
相反Angular 使用 `AppComponent` 自己的注入器注册了 `AppComponent` 的提供
`AppComponent` 服务只在该组件及其子组件树中才能使用。
它们具有*组件级作用域*。
@ -637,24 +637,24 @@ This means that lazy-loaded modules can't reach them.
## Should I add other providers to a module or a component?
## 我应该把其它提供注册到模块中还是组件中?
## 我应该把其它提供注册到模块中还是组件中?
Providers should be configured using `@Injectable` syntax. If possible, they should be provided in the application root (`providedIn: 'root'`). Services that are configured this way are lazily loaded if they are only used from a lazily loaded context.
提供应该使用 `@Injectable` 语法进行配置。只要可能,就应该把它们在应用的根注入器中提供(`providedIn: 'root'`)。
提供应该使用 `@Injectable` 语法进行配置。只要可能,就应该把它们在应用的根注入器中提供(`providedIn: 'root'`)。
如果它们只被惰性加载的上下文中使用,那么这种方式配置的服务就是惰性加载的。
If it's the consumer's decision whether a provider is available application-wide or not,
then register providers in modules (`@NgModule.providers`) instead of registering in components (`@Component.providers`).
如果要由消费方来决定是否把它作为全应用级提供商,那么就要在模块中(`@NgModule.providers`)注册提供商,而不是组件中(`@Component.providers`)。
如果要由消费方来决定是否把它作为全应用级提供者,那么就要在模块中(`@NgModule.providers`)注册提供者,而不是组件中(`@Component.providers`)。
Register a provider with a component when you _must_ limit the scope of a service instance
to that component and its component tree.
Apply the same reasoning to registering a provider with a directive.
当你*必须*把服务实例的范围限制到某个组件及其子组件树时,就把提供注册到该组件中。
指令的提供也同样照此处理。
当你*必须*把服务实例的范围限制到某个组件及其子组件树时,就把提供注册到该组件中。
指令的提供也同样照此处理。
For example, an editing component that needs a private copy of a caching service should register
the service with the component.
@ -704,7 +704,7 @@ Now consider a lazy loaded module that also provides a service called `UserServi
When the router lazy loads a module, it creates a child injector and registers the `UserService`
provider with that child injector. The child injector is _not_ the root injector.
当路由器准备惰性加载 `HeroModule` 的时候,它会创建一个子注入器,并且把 `UserService` 的提供注册到那个子注入器中。子注入器和根注入器是*不同*的。
当路由器准备惰性加载 `HeroModule` 的时候,它会创建一个子注入器,并且把 `UserService` 的提供注册到那个子注入器中。子注入器和根注入器是*不同*的。
When Angular creates a lazy component for that module and injects `UserService`,
it finds a `UserService` provider in the lazy module's _child injector_
@ -713,7 +713,7 @@ This is an entirely different `UserService` instance
than the app-wide singleton version that Angular injected in one of the eagerly loaded components.
当 Angular 创建一个惰性加载的 `HeroComponent` 时,它必须注入一个 `UserService`
这次,它会从惰性加载模块的*子注入器*中查找 `UserService` 的提供,并用它创建一个 `UserService` 的新实例。
这次,它会从惰性加载模块的*子注入器*中查找 `UserService` 的提供,并用它创建一个 `UserService` 的新实例。
这个 `UserService` 实例与 Angular 在主动加载的组件中注入的那个全应用级单例对象截然不同。
This scenario causes your app to create a new instance every time, instead of using the singleton.
@ -739,8 +739,8 @@ I'd like to see the error so I can include it.-->
Angular adds `@NgModule.providers` to the application root injector, unless the NgModule is lazy-loaded.
For a lazy-loaded NgModule, Angular creates a _child injector_ and adds the module's providers to the child injector.
Angular 会把 `@NgModule.providers` 中的提供添加到应用的根注入器中……
除非该模块是惰性加载的这种情况下Angular 会创建一*子注入器*,并且把该模块的提供添加到这个子注入器中。
Angular 会把 `@NgModule.providers` 中的提供添加到应用的根注入器中……
除非该模块是惰性加载的这种情况下Angular 会创建一*子注入器*,并且把该模块的提供添加到这个子注入器中。
This means that an NgModule behaves differently depending on whether it's loaded during application start
or lazy-loaded later. Neglecting that difference can lead to [adverse consequences](guide/ngmodule-faq#q-why-bad).
@ -749,22 +749,22 @@ or lazy-loaded later. Neglecting that difference can lead to [adverse consequenc
Why doesn't Angular add lazy-loaded providers to the app root injector as it does for eagerly loaded NgModules?
为什么 Angular 不能像主动加载模块那样把惰性加载模块的提供也添加到应用程序的根注入器中呢?为什么会出现这种不一致?
为什么 Angular 不能像主动加载模块那样把惰性加载模块的提供也添加到应用程序的根注入器中呢?为什么会出现这种不一致?
The answer is grounded in a fundamental characteristic of the Angular dependency-injection system.
An injector can add providers _until it's first used_.
Once an injector starts creating and delivering services, its provider list is frozen; no new providers are allowed.
归根结底,这来自于 Angular 依赖注入系统的一个基本特征:
在注入器还没有被第一次使用之前,可以不断为其添加提供
一旦注入器已经创建和开始交付服务,它的提供商列表就被冻结了,不再接受新的提供商
在注入器还没有被第一次使用之前,可以不断为其添加提供
一旦注入器已经创建和开始交付服务,它的提供者列表就被冻结了,不再接受新的提供者
When an applications starts, Angular first configures the root injector with the providers of all eagerly loaded NgModules
_before_ creating its first component and injecting any of the provided services.
Once the application begins, the app root injector is closed to new providers.
当应用启动时Angular 会首先使用所有主动加载模块中的提供来配置根注入器,这发生在它创建第一个组件以及注入任何服务之前。
一旦应用开始工作,应用的根注入器就不再接受新的提供了。
当应用启动时Angular 会首先使用所有主动加载模块中的提供来配置根注入器,这发生在它创建第一个组件以及注入任何服务之前。
一旦应用开始工作,应用的根注入器就不再接受新的提供了。
Time passes and application logic triggers lazy loading of an NgModule.
Angular must add the lazy-loaded module's providers to an injector somewhere.
@ -772,8 +772,8 @@ It can't add them to the app root injector because that injector is closed to ne
So Angular creates a new child injector for the lazy-loaded module context.
之后,应用逻辑开始惰性加载某个模块。
Angular 必须把这个惰性加载模块中的提供添加到*某个*注入器中。
但是它无法将它们添加到应用的根注入器中,因为根注入器已经不再接受新的提供了。
Angular 必须把这个惰性加载模块中的提供添加到*某个*注入器中。
但是它无法将它们添加到应用的根注入器中,因为根注入器已经不再接受新的提供了。
于是Angular 在惰性加载模块的上下文中创建了一个新的子注入器。
<hr/>

View File

@ -98,7 +98,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 />
@ -120,4 +120,4 @@ For more information on NgModules, see:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。

View File

@ -13,7 +13,7 @@ making some of them public, through the `exports` property, so that external com
NgModule 是一个带有 `@NgModule` 装饰器的类。
`@NgModule` 的参数是一个元数据对象,用于描述如何编译组件的模板,以及如何在运行时创建注入器。
它会标出该模块自己的组件、指令和管道,通过 `exports` 属性公开其中的一部分,以便外部组件使用它们。
`NgModule` 还能把一些服务提供添加到应用的依赖注入器中。
`NgModule` 还能把一些服务提供添加到应用的依赖注入器中。
For an example app showcasing all the techniques that NgModules related pages
cover, see the <live-example></live-example>. For explanations on the individual techniques, visit the relevant NgModule pages under the NgModules
@ -130,7 +130,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [Types of NgModules](guide/module-types).

View File

@ -122,7 +122,7 @@ Package name | Description
[**@angular/<br />platform&#8209;browser**](api/platform-browser) | Everything DOM and browser related, especially the pieces that help render into the DOM. This package also includes the `bootstrapModuleFactory()` method for bootstrapping applications for production builds that pre-compile with [AOT](guide/aot-compiler).
[**@angular/<br />platform&#8209;browser**](api/platform-browser) | 与 DOM 和浏览器有关的一切,特别是那些帮助往 DOM 中渲染的部分。这个包中还包括 `bootstrapModuleFactory()` 方法,该方法可以使用 [AOT](guide/aot-compiler) 编译器构建的生产环境发布包来引导应用。
[**@angular/<br />platform&#8209;browser&#8209;dynamic**](api/platform-browser-dynamic) | Includes [providers](api/core/Provider) and methods to compile and run the app on the client using the [JIT compiler](guide/aot-compiler).
[**@angular/<br />platform&#8209;browser&#8209;dynamic**](api/platform-browser-dynamic) | 包含那些用来在 [JIT 编译器](guide/aot-compiler)的客户端上编译并运行应用的[提供](api/core/Provider)和方法。
[**@angular/<br />platform&#8209;browser&#8209;dynamic**](api/platform-browser-dynamic) | 包含那些用来在 [JIT 编译器](guide/aot-compiler)的客户端上编译并运行应用的[提供](api/core/Provider)和方法。
[**@angular/router**](api/router) | The router module navigates among your app pages when the browser URL changes. For more information, see [Routing and Navigation](guide/router).
[**@angular/router**](api/router) | 当浏览器的 URL 变化时,路由器模块可以在应用的页面之间进行导航。欲知详情,参见[路由与导航](guide/router)。

View File

@ -1,10 +1,10 @@
# Providers
# 服务提供
# 服务提供
A provider is an instruction to the [Dependency Injection](/guide/dependency-injection) system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide.
提供就是一本说明书,用来指导[依赖注入](/guide/dependency-injection)系统该如何获取某个依赖的值。
提供就是一本说明书,用来指导[依赖注入](/guide/dependency-injection)系统该如何获取某个依赖的值。
大多数情况下,这些依赖就是你要创建和提供的那些服务。
For the final sample app using the provider that this page describes,
@ -38,16 +38,16 @@ You can now inject `UserService` anywhere in your application.
The service itself is a class that the CLI generated and that's decorated with `@Injectable()`. By default, this decorator has a `providedIn` property, which creates a provider for the service. In this case, `providedIn: 'root'` specifies that Angular should provide the service in the root injector.
该服务本身是 CLI 创建的一个类,并且加上了 `@Injectable()` 装饰器。默认情况下,该装饰器是用 `providedIn` 属性进行配置的,它会为该服务创建一个提供。在这个例子中,`providedIn: 'root'` 指定 Angular 应该在根注入器中提供该服务。
该服务本身是 CLI 创建的一个类,并且加上了 `@Injectable()` 装饰器。默认情况下,该装饰器是用 `providedIn` 属性进行配置的,它会为该服务创建一个提供。在这个例子中,`providedIn: 'root'` 指定 Angular 应该在根注入器中提供该服务。
## Provider scope
## 提供的作用域
## 提供的作用域
When you add a service provider to the root application injector, its available throughout the app. Additionally, these providers are also available to all the classes in the app as long they have the lookup token.
当你把服务提供添加到应用的根注入器中时,它就在整个应用程序中可用了。
另外,这些服务提供也同样对整个应用中的类是可用的 —— 只要它们有供查找用的服务令牌。
当你把服务提供添加到应用的根注入器中时,它就在整个应用程序中可用了。
另外,这些服务提供也同样对整个应用中的类是可用的 —— 只要它们有供查找用的服务令牌。
You should always provide your service in the root injector unless there is a case where you want the service to be available only if the consumer imports a particular `@NgModule`.
@ -65,17 +65,17 @@ It's also possible to specify that a service should be provided in a particular
The example above shows the preferred way to provide a service in a module. This method is preferred because it enables tree-shaking of the service if nothing injects it. If it's not possible to specify in the service which module should provide it, you can also declare a provider for the service within the module:
上面的例子展示的就是在模块中提供服务的首选方式。之所以推荐该方式,是因为当没有人注入它时,该服务就可以被摇树优化掉。如果没办法指定哪个模块该提供这个服务,你也可以在那个模块中为该服务声明一个提供
上面的例子展示的就是在模块中提供服务的首选方式。之所以推荐该方式,是因为当没有人注入它时,该服务就可以被摇树优化掉。如果没办法指定哪个模块该提供这个服务,你也可以在那个模块中为该服务声明一个提供
<code-example path="providers/src/app/user.module.ts" header="src/app/user.module.ts"></code-example>
## Limiting provider scope by lazy loading modules
## 使用惰性加载模块限制提供的作用域
## 使用惰性加载模块限制提供的作用域
In the basic CLI-generated app, modules are eagerly loaded which means that they are all loaded when the app launches. Angular uses an injector system to make things available between modules. In an eagerly loaded app, the root application injector makes all of the providers in all of the modules available throughout the app.
在 CLI 生成的基本应用中模块是急性加载的这意味着它们都是由本应用启动的Angular 会使用一个依赖注入体系来让一切服务都在模块间有效。对于急性加载式应用,应用中的根注入器会让所有服务提供都对整个应用有效。
在 CLI 生成的基本应用中模块是急性加载的这意味着它们都是由本应用启动的Angular 会使用一个依赖注入体系来让一切服务都在模块间有效。对于急性加载式应用,应用中的根注入器会让所有服务提供都对整个应用有效。
This behavior necessarily changes when you use lazy loading. Lazy loading is when you load modules only when you need them; for example, when routing. They arent loaded right away like with eagerly loaded modules. This means that any services listed in their provider arrays arent available because the root injector doesnt know about these modules.
@ -87,7 +87,7 @@ This behavior necessarily changes when you use lazy loading. Lazy loading is whe
When the Angular router lazy-loads a module, it creates a new injector. This injector is a child of the root application injector. Imagine a tree of injectors; there is a single root injector and then a child injector for each lazy loaded module. The router adds all of the providers from the root injector to the child injector. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.
当 Angular 的路由器惰性加载一个模块时,它会创建一个新的注入器。这个注入器是应用的根注入器的一个子注入器。想象一棵注入器树,它有唯一的根注入器,而每一个惰性加载模块都有一个自己的子注入器。路由器会把根注入器中的所有提供添加到子注入器中。如果路由器在惰性加载时创建组件, Angular 会更倾向于使用从这些提供中创建的服务实例,而不是来自应用的根注入器的服务实例。
当 Angular 的路由器惰性加载一个模块时,它会创建一个新的注入器。这个注入器是应用的根注入器的一个子注入器。想象一棵注入器树,它有唯一的根注入器,而每一个惰性加载模块都有一个自己的子注入器。路由器会把根注入器中的所有提供添加到子注入器中。如果路由器在惰性加载时创建组件, Angular 会更倾向于使用从这些提供中创建的服务实例,而不是来自应用的根注入器的服务实例。
Any component created within a lazy loaded modules context, such as by router navigation, gets the local instance of the service, not the instance in the root application injector. Components in external modules continue to receive the instance created for the application root.
@ -99,7 +99,7 @@ Though you can provide services by lazy loading modules, not all services can be
## Limiting provider scope with components
## 使用组件限定服务提供的作用域
## 使用组件限定服务提供的作用域
Another way to limit provider scope is by adding the service you want to limit to the components
`providers` array. Component providers and NgModule providers are independent of each other. This
@ -107,7 +107,7 @@ method is helpful when you want to eagerly load a module that needs a service al
Providing a service in the component limits the service only to that component (other components in
the same module cant access it).
另一种限定提供作用域的方式是把要限定的服务添加到组件的 `providers` 数组中。组件中的提供商和 NgModule 中的提供商是彼此独立的。
另一种限定提供作用域的方式是把要限定的服务添加到组件的 `providers` 数组中。组件中的提供者和 NgModule 中的提供者是彼此独立的。
当你要急性加载一个自带了全部所需服务的模块时,这种方式是有帮助的。
在组件中提供服务,会限定该服务只能在该组件中有效(同一模块中的其它组件不能访问它)。
@ -123,13 +123,13 @@ Generally, provide services the whole app needs in the root module and scope ser
The router works at the root level so if you put providers in a component, even `AppComponent`, lazy loaded modules, which rely on the router, cant see them.
路由器工作在根级,所以如果你把服务提供放进组件(即使是 `AppComponent`)中,那些依赖于路由器的惰性加载模块,将无法看到它们。
路由器工作在根级,所以如果你把服务提供放进组件(即使是 `AppComponent`)中,那些依赖于路由器的惰性加载模块,将无法看到它们。
<!-- KW--Make a diagram here -->
Register a provider with a component when you must limit a service instance to a component and its component tree, that is, its child components. For example, a user editing component, `UserEditorComponent`, that needs a private copy of a caching `UserService` should register the `UserService` with the `UserEditorComponent`. Then each new instance of the `UserEditorComponent` gets its own cached service instance.
当你必须把一个服务实例的作用域限定到组件及其组件树中时,可以使用组件注册一个服务提供
当你必须把一个服务实例的作用域限定到组件及其组件树中时,可以使用组件注册一个服务提供
比如,用户编辑组件 `UserEditorComponent`,它需要一个缓存 `UserService` 实例,那就应该把 `UserService` 注册进 `UserEditorComponent` 中。
然后,每个 `UserEditorComponent` 的实例都会获取它自己的缓存服务实例。
@ -153,7 +153,7 @@ You may also be interested in:
* [Tree-shakable Providers](guide/dependency-injection-providers#tree-shakable-providers).
[可摇树优化的服务提供](guide/dependency-injection-providers#tree-shakable-providers)。
[可摇树优化的服务提供](guide/dependency-injection-providers#tree-shakable-providers)。
* [NgModule FAQ](guide/ngmodule-faq).

View File

@ -439,7 +439,7 @@ Import the `FormBuilder` class from the `@angular/forms` package.
The `FormBuilder` service is an injectable provider that is provided with the reactive forms module. Inject this dependency by adding it to the component constructor.
`FormBuilder` 是一个可注入的服务提供,它是由 `ReactiveFormModule` 提供的。只要把它添加到组件的构造函数中就可以注入这个依赖。
`FormBuilder` 是一个可注入的服务提供,它是由 `ReactiveFormModule` 提供的。只要把它添加到组件的构造函数中就可以注入这个依赖。
<code-example path="reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" region="inject-form-builder" header="src/app/profile-editor/profile-editor.component.ts (constructor)">

View File

@ -74,7 +74,7 @@ Use the `RouterModule.forRoot` method to define a set of routes. Also, import th
**Note:** Use the `RouterModule.forRoot` method in the root module, `AppModule`, to register top-level application routes and providers. For feature modules, call the `RouterModule.forChild` method to register additional routes.
**注意:**在根模块 `AppModule` 中使用 `RouterModule.forRoot` 方法来注册一些顶层应用路由和提供。对于特性模块,调用 `RouterModule.forChild` 方法来注册其它路由。
**注意:**在根模块 `AppModule` 中使用 `RouterModule.forRoot` 方法来注册一些顶层应用路由和提供。对于特性模块,调用 `RouterModule.forChild` 方法来注册其它路由。
</div>

View File

@ -885,7 +885,7 @@ Here are the key `Router` terms and their meanings:
A separate NgModule that provides the necessary service providers
and directives for navigating through application views.
一个独立的 NgModule用于提供所需的服务提供,以及用来在应用视图之间进行导航的指令。
一个独立的 NgModule用于提供所需的服务提供,以及用来在应用视图之间进行导航的指令。
</td>
@ -1364,14 +1364,14 @@ In order to use the Router, you must first register the `RouterModule` from the
要使用路由器,必须先注册来自 `@angular/router` 包中的 `RouterModule`
定义一个路由数组 `appRoutes` 并把它传给 `RouterModule.forRoot()` 方法。
它会返回一个模块,其中包含配置好的 `Router` 服务提供商,以及路由库所需的其它提供商
它会返回一个模块,其中包含配置好的 `Router` 服务提供者,以及路由库所需的其它提供者
一旦启动了应用,`Router` 就会根据当前的浏览器 URL 进行首次导航。
<div class="alert is-important">
**Note:** The `RouterModule.forRoot` method is a pattern used to register application-wide providers. Read more about application-wide providers in the [Singleton services](guide/singleton-services#forRoot-router) guide.
**注意:** `RouterModule.forRoot` 方法是用于注册全应用级提供商的编码模式。要详细了解全应用级提供商,参见[单例服务](guide/singleton-services#forRoot-router) 一章。
**注意:** `RouterModule.forRoot` 方法是用于注册全应用级提供者的编码模式。要详细了解全应用级提供者,参见[单例服务](guide/singleton-services#forRoot-router) 一章。
</div>
@ -1849,7 +1849,7 @@ The **Routing Module** has several characteristics:
* Provides a well-known location for routing service providers including guards and resolvers.
为路由服务提供(包括守卫和解析器等)提供一个共同的地方。
为路由服务提供(包括守卫和解析器等)提供一个共同的地方。
* Does **not** declare components.
@ -2239,7 +2239,7 @@ In the `AppRoutingModule`, you used the static **`RouterModule.forRoot()`** meth
In a feature module you use the static **`forChild`** method.
这里有少量但是关键的不同点。
`AppRoutingModule` 中,你使用了静态的 `RouterModule.`**`forRoot`**方法来注册路由和全应用级服务提供
`AppRoutingModule` 中,你使用了静态的 `RouterModule.`**`forRoot`**方法来注册路由和全应用级服务提供
在特性模块中,你要改用**`forChild`**静态方法。
<div class="alert is-helpful">
@ -5929,7 +5929,7 @@ URLs with hashes. Here's a "hash URL" that routes to the *Crisis Center*.
The router supports both styles with two `LocationStrategy` providers:
路由器通过两种 `LocationStrategy` 提供来支持所有这些风格:
路由器通过两种 `LocationStrategy` 提供来支持所有这些风格:
1. `PathLocationStrategy`&mdash;the default "HTML5 pushState" style.
@ -5951,7 +5951,7 @@ You can switch to the `HashLocationStrategy` with an override during the bootstr
Learn about providers and the bootstrap process in the
[Dependency Injection guide](guide/dependency-injection#bootstrap).
要学习关于“提供”和启动过程的更多知识,参见[依赖注入](guide/dependency-injection#bootstrap)一章。
要学习关于“提供”和启动过程的更多知识,参见[依赖注入](guide/dependency-injection#bootstrap)一章。
</div>

View File

@ -81,7 +81,7 @@ The most common way to get a hold of shared services is through Angular
To read about sharing services, see [Providers](guide/providers).
要进一步了解共享服务,参见[服务提供](guide/providers)。
要进一步了解共享服务,参见[服务提供](guide/providers)。
<hr />
@ -95,7 +95,7 @@ You may also be interested in the following:
* [Providers](guide/providers).
[服务提供](guide/providers)。
[服务提供](guide/providers)。
* [Types of Feature Modules](guide/module-types).

View File

@ -112,7 +112,7 @@ Use `forRoot()` to
separate providers from a module so you can import that module into the root module
with `providers` and child modules without `providers`.
使用 `forRoot()` 来把提供从该模块中分离出去,这样你就能在根模块中导入该模块时带上 `providers` ,并且在子模块中导入它时不带 `providers`
使用 `forRoot()` 来把提供从该模块中分离出去,这样你就能在根模块中导入该模块时带上 `providers` ,并且在子模块中导入它时不带 `providers`
1. Create a static method `forRoot()` on the module.
@ -120,7 +120,7 @@ with `providers` and child modules without `providers`.
2. Place the providers into the `forRoot()` method.
把这些提供放进 `forRoot()` 方法中。
把这些提供放进 `forRoot()` 方法中。
<code-example path="ngmodules/src/app/greeting/greeting.module.ts" region="for-root" header="src/app/greeting/greeting.module.ts"></code-example>
@ -168,7 +168,7 @@ a simple object with the following properties:
* `providers`: the configured providers.
`providers` - 配置好的服务提供
`providers` - 配置好的服务提供
In the <live-example name="ngmodules">live example</live-example>
the root `AppModule` imports the `GreetingModule` and adds the
@ -179,7 +179,7 @@ This sequence ensures that whatever you add explicitly to
the `AppModule` providers takes precedence over the providers
of imported modules.
在这个 <live-example name="ngmodules">现场演练</live-example>中,根模块 `AppModule` 导入了 `GreetingModule`,并把它的 `providers` 添加到了 `AppModule` 的服务提供商列表中。特别是Angular 会把所有从其它模块导入的提供商追加到本模块的 `@NgModule.providers` 中列出的提供商之前。这种顺序可以确保你在 `AppModule``providers` 中显式列出的提供商,其优先级高于导入模块中给出的提供商
在这个 <live-example name="ngmodules">现场演练</live-example>中,根模块 `AppModule` 导入了 `GreetingModule`,并把它的 `providers` 添加到了 `AppModule` 的服务提供者列表中。特别是Angular 会把所有从其它模块导入的提供者追加到本模块的 `@NgModule.providers` 中列出的提供者之前。这种顺序可以确保你在 `AppModule``providers` 中显式列出的提供者,其优先级高于导入模块中给出的提供者
The sample app imports `GreetingModule` and uses its `forRoot()` method one time, in `AppModule`. Registering it once like this prevents multiple instances.
@ -255,7 +255,7 @@ The `@Optional()` decorator means not finding the service is OK.
The injector returns `null`, the `parentModule` parameter is null,
and the constructor concludes uneventfully.
默认情况下,当注入器找不到想找的提供时,会抛出一个错误。
默认情况下,当注入器找不到想找的提供时,会抛出一个错误。
`@Optional()` 装饰器表示找不到该服务也无所谓。
于是注入器会返回 `null``parentModule` 参数也就被赋成了空值,而构造函数没有任何异常。

View File

@ -2636,7 +2636,7 @@ that may need features from another common module; for example,
**Avoid** specifying app-wide singleton providers in a `SharedModule`. Intentional singletons are OK. Take care.
**避免**在 `SharedModule` 中指定应用级的单例服务提供。如果是刻意要得到多个服务单例也行,不过还是要小心。
**避免**在 `SharedModule` 中指定应用级的单例服务提供。如果是刻意要得到多个服务单例也行,不过还是要小心。
</div>

View File

@ -1006,7 +1006,7 @@ Later you'll call `TestBed.configureTestingModule()` with
imports, providers, and more declarations to suit your testing needs.
Optional `override` methods can further fine-tune aspects of the configuration.
稍后你将会调用带有导入模块、服务提供和更多可声明对象的 `TestBed.configureTestingModule()` 来满足测试所需。
稍后你将会调用带有导入模块、服务提供和更多可声明对象的 `TestBed.configureTestingModule()` 来满足测试所需。
将来还可以用可选的 `override` 方法对这些配置进行微调。
</div>
@ -1414,7 +1414,7 @@ Some testers prefer that the Angular test environment run change detection autom
That's possible by configuring the `TestBed` with the `ComponentFixtureAutoDetect` provider.
First import it from the testing utility library:
使用 `ComponentFixtureAutoDetect` 服务提供来配置 `TestBed` 就可以做到这一点。
使用 `ComponentFixtureAutoDetect` 服务提供来配置 `TestBed` 就可以做到这一点。
首先从测试工具库中导入它:
<code-example path="testing/src/app/banner/banner.component.detect-changes.spec.ts" region="import-ComponentFixtureAutoDetect" header="app/banner/banner.component.detect-changes.spec.ts (import)"></code-example>
@ -1651,7 +1651,7 @@ But it only works when Angular injects the component with the service instance i
In this test suite, the _only_ provider of `UserService` is the root testing module,
so it is safe to call `TestBed.inject()` as follows:
在这个测试套件中,`UserService` *唯一*的提供就是根测试模块中的,因此调用 `TestBed.inject()` 就是安全的,代码如下:
在这个测试套件中,`UserService` *唯一*的提供就是根测试模块中的,因此调用 `TestBed.inject()` 就是安全的,代码如下:
<code-example
path="testing/src/app/welcome/welcome.component.spec.ts"
@ -1665,7 +1665,7 @@ For a use case in which `TestBed.inject()` does not work,
see the [_Override component providers_](#component-override) section that
explains when and why you must get the service from the component's injector instead.
对于那些不能用 `TestBed.inject()` 的测试用例,请参见[改写组件的提供](#component-override)一节,那里解释了何时以及为何必须改从组件自身的注入器中获取服务。
对于那些不能用 `TestBed.inject()` 的测试用例,请参见[改写组件的提供](#component-override)一节,那里解释了何时以及为何必须改从组件自身的注入器中获取服务。
</div>
@ -3788,7 +3788,7 @@ But more complex components often depend on other components, directives, pipes,
and these must be added to the testing module too.
`DashbaordComponent` 非常简单。它不需要帮助。
但是更加复杂的组件通常依赖其它组件、指令、管道和提供
但是更加复杂的组件通常依赖其它组件、指令、管道和提供
所以这些必须也被添加到测试模块中。
Fortunately, the `TestBed.configureTestingModule` parameter parallels
@ -3906,7 +3906,7 @@ the module is small, as feature modules tend to be.
### Override component providers
### 改写组件的服务提供
### 改写组件的服务提供
The `HeroDetailComponent` provides its own `HeroDetailService`.
@ -3918,13 +3918,13 @@ It's not possible to stub the component's `HeroDetailService` in the `providers`
Those are providers for the _testing module_, not the component. They prepare the dependency injector at the _fixture level_.
`TestBed.configureTestingModule``providers` 中 stub 伪造组件的 `HeroDetailService` 是不可行的。
这些是**测试模块**的提供,而非组件的。组件级别的供应商应该在**fixture 级别**准备的依赖注入器。
这些是**测试模块**的提供,而非组件的。组件级别的供应商应该在**fixture 级别**准备的依赖注入器。
Angular creates the component with its _own_ injector, which is a _child_ of the fixture injector.
It registers the component's providers (the `HeroDetailService` in this case) with the child injector.
Angular 会使用自己的注入器来创建这些组件,这个注入器是夹具的注入器的子注入器。
它使用这个子注入器注册了该组件服务提供(这里是 `HeroDetailService` )。
它使用这个子注入器注册了该组件服务提供(这里是 `HeroDetailService` )。
A test cannot get to child injector services from the fixture injector.
And `TestBed.configureTestingModule` can't configure them either.
@ -4487,7 +4487,7 @@ Here's a summary of the stand-alone functions, in order of likely utility:
A provider token for a service that turns on [automatic change detection](#automatic-change-detection).
一个服务提供令牌,用于开启[自动变更检测](#automatic-change-detection)。
一个服务提供令牌,用于开启[自动变更检测](#automatic-change-detection)。
</td>
@ -4625,7 +4625,7 @@ Here are the most important static methods, in order of likely utility.
Call `configureTestingModule` to refine the testing module configuration for a particular set of tests
by adding and removing imports, declarations (of components, directives, and pipes), and providers.
调用 `configureTestingModule` 来为一套特定的测试定义测试模块配置,添加和删除导入、(组件、指令和管道的)声明和服务提供
调用 `configureTestingModule` 来为一套特定的测试定义测试模块配置,添加和删除导入、(组件、指令和管道的)声明和服务提供
</td>
</tr>
@ -4783,7 +4783,7 @@ Here are the most important static methods, in order of likely utility.
the object to return if Angular can't find the provider
(`null` in this example):
`TestBed.inject()` 方法可以接受可选的第二参数,当 Angular 找不到指定的服务提供时,就会返回该对象(下面这个例子中是 `null`
`TestBed.inject()` 方法可以接受可选的第二参数,当 Angular 找不到指定的服务提供时,就会返回该对象(下面这个例子中是 `null`
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="testbed-get-w-null" header="app/demo/demo.testbed.spec.ts"></code-example>

View File

@ -469,7 +469,7 @@ You can do this when your app needs information that can only be determined by t
One example could be the running server's *origin*, which could be used to [calculate absolute HTTP URLs](#http-urls) if
not using the `Request` token as shown above.
第二个参数 `extraProviders` 是可选的。它能让你指定一些在服务端运行时特有的服务提供
第二个参数 `extraProviders` 是可选的。它能让你指定一些在服务端运行时特有的服务提供
只有当你的应用需要一些运行在服务器中才需要的信息时,才需要这么做。
比如这个运行中的服务器的*源*地址,当像前面例子中那样无法使用 `Request` 令牌时,可用它来[计算 HTTP URL 的绝对地址](#http-urls)。

View File

@ -183,7 +183,7 @@ Read about the migrations the CLI handles for you automatically:
- [Migrating missing `@Injectable()` decorators and incomplete provider definitions](guide/migration-injectable)
[迁移缺失的 `@Injectable()` 装饰器和不完整的服务提供定义](guide/migration-injectable)
[迁移缺失的 `@Injectable()` 装饰器和不完整的服务提供定义](guide/migration-injectable)
- [Migrating dynamic queries](guide/migration-dynamic-flag)

View File

@ -716,7 +716,7 @@ It also imports `UpgradeModule` from `@angular/upgrade/static`, which exports pr
for upgrading and downgrading services and components.
最小化的 `NgModule` 导入了 `BrowserModule`,它是每个基于浏览器的 Angular 应用必备的。
它还从 `@angular/upgrade/static` 中导入了 `UpgradeModule`,它导出了一些服务提供商,这些提供商会用于升级、降级服务和组件。
它还从 `@angular/upgrade/static` 中导入了 `UpgradeModule`,它导出了一些服务提供者,这些提供者会用于升级、降级服务和组件。
In the constructor of the `AppModule`, use dependency injection to get a hold of the `UpgradeModule` instance,
and use it to bootstrap the AngularJS app in the `AppModule.ngDoBootstrap` method.
@ -1193,7 +1193,7 @@ In these situations, it is possible to *upgrade* an AngularJS provider to
Angular. This makes it possible to then inject it somewhere in Angular
code. For example, you might have a service called `HeroesService` in AngularJS:
在这些情况下,把一个 AngularJS 提供*升级到*Angular 也是有可能的。这就让它将来有可能被注入到 Angular 代码中的某些地方。
在这些情况下,把一个 AngularJS 提供*升级到*Angular 也是有可能的。这就让它将来有可能被注入到 Angular 代码中的某些地方。
比如,你可能在 AngularJS 中有一个名叫 `HeroesService` 的服务:
<code-example path="upgrade-module/src/app/ajs-to-a-providers/heroes.service.ts" header="heroes.service.ts">
@ -1202,14 +1202,14 @@ code. For example, you might have a service called `HeroesService` in AngularJS:
You can upgrade the service using a Angular [factory provider](guide/dependency-injection-providers#factory-providers)
that requests the service from the AngularJS `$injector`.
你可以用 Angular 的[工厂提供](guide/dependency-injection-providers#factory-providers)升级该服务,
你可以用 Angular 的[工厂提供](guide/dependency-injection-providers#factory-providers)升级该服务,
它从 AngularJS 的 `$injector` 请求服务。
Many developers prefer to declare the factory provider in a separate `ajs-upgraded-providers.ts` file
so that they are all together, making it easier to reference them, create new ones and
delete them once the upgrade is over.
很多开发者都喜欢在一个独立的 `ajs-upgraded-providers.ts` 中声明这个工厂提供,以便把它们都放在一起,这样便于引用、创建新的以及在升级完毕时删除它们。
很多开发者都喜欢在一个独立的 `ajs-upgraded-providers.ts` 中声明这个工厂提供,以便把它们都放在一起,这样便于引用、创建新的以及在升级完毕时删除它们。
It's also recommended to export the `heroesServiceFactory` function so that Ahead-of-Time
compilation can pick it up.
@ -1254,7 +1254,7 @@ provider can be upgraded.
在这个例子中,你升级了服务类。当注入它时,你可以使用 TypeScript 类型注解来获得这些额外的好处。
它没有影响该依赖的处理过程,同时还得到了启用静态类型检查的好处。
任何 AngularJS 中的服务、工厂和提供都能被升级 —— 尽管这不是必须的。
任何 AngularJS 中的服务、工厂和提供都能被升级 —— 尽管这不是必须的。
</div>
@ -1279,7 +1279,7 @@ For example, you might have an Angular service called `Heroes`:
Again, as with Angular components, register the provider with the `NgModule` by adding it to the module's `providers` list.
仿照 Angular 组件,把该提供加入 `NgModule``providers` 列表中,以注册它。
仿照 Angular 组件,把该提供加入 `NgModule``providers` 列表中,以注册它。
<code-example path="upgrade-module/src/app/a-to-ajs-providers/app.module.ts" region="ngmodule" header="app.module.ts">
</code-example>
@ -1506,12 +1506,12 @@ LocationUpgradeModule.config({
This registers a drop-in replacement for the `$location` provider in AngularJS. Once registered, all navigation, routing broadcast messages, and any necessary digest cycles in AngularJS triggered during navigation are handled by Angular. This gives you a single way to navigate within both sides of your hybrid application consistently.
这会为 AngularJS 中的 `$location` 提供注册一个替代品。一旦注册成功,导航过程中所有由 AngularJS 触发的导航、路由广播消息以及任何必需的变更检测周期都会改由 Angular 进行处理。这样,你就可以通过这个唯一的途径在此混合应用的两个框架间进行导航了。
这会为 AngularJS 中的 `$location` 提供注册一个替代品。一旦注册成功,导航过程中所有由 AngularJS 触发的导航、路由广播消息以及任何必需的变更检测周期都会改由 Angular 进行处理。这样,你就可以通过这个唯一的途径在此混合应用的两个框架间进行导航了。
For usage of the `$location` service as a provider in AngularJS, you need to downgrade the `$locationShim` using a factory provider.
要想在 AngularJS 中使用 `$location` 服务作为提供商,你需要使用一个工厂提供商来降级 `$locationShim`
要想在 AngularJS 中使用 `$location` 服务作为提供者,你需要使用一个工厂提供者来降级 `$locationShim`
```ts
@ -2583,8 +2583,8 @@ to make `$routeParams` an Angular injectable.
Do that in a new file called `ajs-upgraded-providers.ts` and import it in `app.module.ts`:
不幸的是AngularJS 的依赖不会自动在 Angular 的组件中可用。
你必须使用[工厂提供factory provider](guide/upgrade#making-angularjs-dependencies-injectable-to-angular)
来把 `$routeParams` 包装成 Angular 的服务提供
你必须使用[工厂提供factory provider](guide/upgrade#making-angularjs-dependencies-injectable-to-angular)
来把 `$routeParams` 包装成 Angular 的服务提供
新建一个名叫 `ajs-upgraded-providers.ts` 的文件,并且在 `app.module.ts` 中导入它:
<code-example path="upgrade-phonecat-2-hybrid/app/ajs-upgraded-providers.ts" header="app/ajs-upgraded-providers.ts">
@ -2807,7 +2807,7 @@ It passes the `routes` to the `RouterModule.forRoot` method which does the rest.
A couple of extra providers enable routing with "hash" URLs such as `#!/phones`
instead of the default "push state" strategy.
一些额外的提供让路由器使用“hash”策略解析 URL比如 `#!/phones`而不是默认的“Push State”策略。
一些额外的提供让路由器使用“hash”策略解析 URL比如 `#!/phones`而不是默认的“Push State”策略。
Now update the `AppModule` to import this `AppRoutingModule` and also the
declare the root `AppComponent` as the bootstrap component.

View File

@ -344,8 +344,8 @@
},
{
"url": "guide/providers",
"title": "服务提供",
"tooltip": "服务提供与 NgModule"
"title": "服务提供",
"tooltip": "服务提供与 NgModule"
},
{
"url": "guide/singleton-services",
@ -390,8 +390,8 @@
},
{
"url": "guide/dependency-injection-providers",
"title": "DI 提供",
"tooltip": "各种提供类型的更多知识。"
"title": "DI 提供",
"tooltip": "各种提供类型的更多知识。"
},
{
"url": "guide/dependency-injection-in-action",

View File

@ -415,7 +415,7 @@ Before you can use Angular's HTTP client, you must configure your app to use `Ht
Angular's `HttpClientModule` registers the providers your app needs to use a single instance of the `HttpClient` service throughout your app.
Angular 的 `HttpClientModule` 中注册了在整个应用中使用 `HttpClient` 服务的单个实例所需的服务提供
Angular 的 `HttpClientModule` 中注册了在整个应用中使用 `HttpClient` 服务的单个实例所需的服务提供
1. Open `app.module.ts`.

View File

@ -121,17 +121,17 @@ Add a `getHeroes` method to return the _mock heroes_.
You must make the `HeroService` available to the dependency injection system
before Angular can _inject_ it into the `HeroesComponent` by registering a _provider_. A provider is something that can create or deliver a service; in this case, it instantiates the `HeroService` class to provide the service.
你必须先注册一个*服务提供*,来让 `HeroService` 在依赖注入系统中可用Angular 才能把它注入到 `HeroesComponent` 中。所谓服务提供就是某种可用来创建或交付一个服务的东西;在这里,它通过实例化 `HeroService` 类,来提供该服务。
你必须先注册一个*服务提供*,来让 `HeroService` 在依赖注入系统中可用Angular 才能把它注入到 `HeroesComponent` 中。所谓服务提供就是某种可用来创建或交付一个服务的东西;在这里,它通过实例化 `HeroService` 类,来提供该服务。
To make sure that the `HeroService` can provide this service, register it
with the _injector_, which is the object that is responsible for choosing
and injecting the provider where the app requires it.
为了确保 `HeroService` 可以提供该服务,就要使用*注入器*来注册它。注入器是一个对象,负责当应用要求获取它的实例时选择和注入该提供
为了确保 `HeroService` 可以提供该服务,就要使用*注入器*来注册它。注入器是一个对象,负责当应用要求获取它的实例时选择和注入该提供
By default, the Angular CLI command `ng generate service` registers a provider with the _root injector_ for your service by including provider metadata, that is `providedIn: 'root'` in the `@Injectable()` decorator.
默认情况下Angular CLI 命令 `ng generate service` 会通过给 `@Injectable()` 装饰器添加 `providedIn: 'root'` 元数据的形式,用*根注入器*将你的服务注册成为提供
默认情况下Angular CLI 命令 `ng generate service` 会通过给 `@Injectable()` 装饰器添加 `providedIn: 'root'` 元数据的形式,用*根注入器*将你的服务注册成为提供
```
@ -145,14 +145,14 @@ When you provide the service at the root level, Angular creates a single, shared
Registering the provider in the `@Injectable` metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
当你在顶层提供该服务时Angular 就会为 `HeroService` 创建一个单一的、共享的实例,并把它注入到任何想要它的类上。
`@Injectable` 元数据中注册该提供,还能允许 Angular 通过移除那些完全没有用过的服务来进行优化。
`@Injectable` 元数据中注册该提供,还能允许 Angular 通过移除那些完全没有用过的服务来进行优化。
<div class="alert is-helpful">
To learn more about providers, see the [Providers section](guide/providers).
To learn more about injectors, see the [Dependency Injection guide](guide/dependency-injection).
要了解关于提供商的更多知识,参见[提供商部分](guide/providers)。
要了解关于提供者的更多知识,参见[提供者部分](guide/providers)。
要了解关于注入器的更多知识,参见[依赖注入指南](guide/dependency-injection)。
</div>
@ -678,7 +678,7 @@ Here are the code files discussed on this page and your app should look like thi
* You registered the `HeroService` as the _provider_ of its service at the root level so that it can be injected anywhere in the app.
你在根注入器中把 `HeroService` 注册为该服务的提供,以便在别处可以注入它。
你在根注入器中把 `HeroService` 注册为该服务的提供,以便在别处可以注入它。
* You used [Angular Dependency Injection](guide/dependency-injection) to inject it into a component.

View File

@ -144,7 +144,7 @@ configures it with the `routes` in one step by calling
and performs the initial navigation based on the current browser URL.
这个方法之所以叫 `forRoot()`,是因为你要在应用的顶层配置这个路由器。
`forRoot()` 方法会提供路由所需的服务提供和指令,还会基于浏览器的当前 URL 执行首次导航。
`forRoot()` 方法会提供路由所需的服务提供和指令,还会基于浏览器的当前 URL 执行首次导航。
</div>