Edits copy and removes tokens and treeshaking
sections to reduce content duplication and keep
info focused. Moves provideParent() from di-navtree
to di providers.
PR Close#39403
@ -93,7 +93,7 @@ or in the `@NgModule()` or `@Component()` metadata
When you provide the service at the root level, Angular creates a single, shared instance of `HeroService`
and injects it into any class that asks for it.
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.
by removing the service from the compiled app if it isn't used, a process known as *tree-shaking*.
* 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.
@ -79,7 +79,7 @@ Here are some things to consider in migrating application functionality to a lib
* Consider how you provide services to client applications.
* 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).
* Services should declare their own providers, rather than declaring providers in the NgModule or a component. Declaring a provider makes that service *tree-shakable*. This practice 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/architecture-services#providing-services).
* If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` design patterns](guide/singleton-services) provided by the [RouterModule](api/router/RouterModule).
A dependency [provider](guide/glossary#provider) configures an injector
with a [DI token](guide/glossary#di-token),
which that injector uses to provide the concrete, runtime version of a dependency value.
The injector relies on the provider configuration to create instances of the dependencies
that it injects into components, directives, pipes, and other services.
By configuring providers, you can make services available to the parts of your application that need them.
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`.
A dependency [provider](guide/glossary#provider) configures an injector with a [DI token](guide/glossary#di-token), which that injector uses to provide the runtime version of a dependency value.
In the following typical example, the `Logger` class itself provides a `Logger` instance.
## Specifying a provider token
If you specify the service class as the provider token, the default behavior is for the injector to instantiate that class with `new`.
In the following example, the `Logger` class provides a `Logger` instance.
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.
You can, however, configure an injector with an alternative provider in order to deliver some other object that provides the needed logging functionality.
* You can provide a logger-like object.
* Your provider can call a logger factory function.
You can configure an injector with a service class, you can provide a substitute class, an object, or a factory function.
{@a provide}
## The `Provider` object literal
## Defining providers
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.
The class provider syntax is a shorthand expression that expands into a provider configuration, defined by the [`Provider` interface](api/core/Provider).
The following example is the class provider syntax for providing a `Logger` class in the `providers` array.
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.
* The second property is a provider definition object, which tells the injector how to create the dependency value.
1. 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.
2. The second property is a provider definition object, which tells the injector how to create the dependency value.
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.
@ -51,185 +43,168 @@ Each of these keys provides a different type of dependency, as discussed below.
{@a class-provider}
## Alternative class providers
## Configuring the injector to use alternative class providers
Different classes can provide the same service.
For example, the following code tells the injector
to return a `BetterLogger` instance when the component asks for a logger
using the `Logger` token.
To configure the injector to return a different class that provides the same service, you can use the `useClass` property.
In this example, the injector returns a `BetterLogger` instance when using the `Logger` token.
Another class, `EvenBetterLogger`, might display the user name in the log message.
If the alternative class providers have their own dependencies, specify both providers in the `providers` metadata property of the parent module or component.
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.
Although the `AppConfig` interface plays no role in dependency injection,
it supports typing of the configuration object within the class.
</div>
{@a factory-provider}
{@a factory-providers}
## Factory providers
## Using factory providers
Sometimes you need to create a dependent value dynamically,
based on information you won't have until run time.
For example, you might need information that changes repeatedly in the course of the browser session.
Also, your injectable service might not have independent access to the source of the information.
To create a changeable, dependent value based on information unavailable before run time, you can use a factory provider.
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.
In the following example, only authorized users should see secret heroes in the `HeroService`.
Authorization can change during the course of a single application session, as when a different user logs in .
For example, suppose `HeroService` must hide *secret* heroes from normal users.
Only authorized users should see secret heroes.
Like `EvenBetterLogger`, `HeroService` needs to know if the user is authorized to see secret heroes.
That authorization can change during the course of a single application session,
as when you log in a different user.
Imagine that you don't want to inject `UserService` directly into `HeroService`, because you don't want to complicate that service with security-sensitive information.
`HeroService` won't have direct access to the user information to decide
who is authorized and who isn't.
To resolve this, give the `HeroService` constructor a boolean flag to control display of secret heroes.
To keep security-sensitive information in `UserService` and out of `HeroService`, give the `HeroService` constructor a boolean flag to control display of secret heroes.
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`.
A factory provider needs a factory function.
To implement the `isAuthorized` flag, use a factory provider to create a new logger instance for `HeroService`.
* The `useFactory` field tells Angular that the provider is a factory function whose implementation is `heroServiceFactory`.
* The `useFactory` field specifies that the provider is a factory function whose implementation is `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.
The injector resolves these tokens and injects the corresponding services into the matching `heroServiceFactory` factory function parameters.
Notice that you captured the factory provider in an exported variable, `heroServiceProvider`.
This extra step makes the factory provider reusable.
You can configure a provider of `HeroService` with this variable wherever you need it.
In this sample, you need it only in `HeroesComponent`,
where `heroServiceProvider` replaces `HeroService` in the metadata `providers` array.
Capturing the factory provider in the exported variable, `heroServiceProvider`, makes the factory provider reusable.
The following shows the new and the old implementations side-by-side.
The following side-by-side example shows how `heroServiceProvider` replaces `HeroService` in the `providers` array.
<code-tabs>
@ -241,115 +216,3 @@ The following shows the new and the old implementations side-by-side.
</code-tabs>
## 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.
For example, you can use the following built-in tokens as hooks into the framework’s bootstrapping and initialization process.
A provider object can associate any of these injection tokens with one or more callback functions that take app-specific initialization actions.
* [PLATFORM_INITIALIZER](api/core/PLATFORM_INITIALIZER): Callback is invoked when a platform is initialized.
* [APP_BOOTSTRAP_LISTENER](api/core/APP_BOOTSTRAP_LISTENER): Callback is invoked for each component that is bootstrapped. The handler function receives the ComponentRef instance of the bootstrapped component.
* [APP_INITIALIZER](api/core/APP_INITIALIZER): Callback is invoked before an app is initialized. All registered initializers can optionally return a Promise. All initializer functions that return Promises must be resolved before the application is bootstrapped. If one of the initializers fails to resolves, the application is not bootstrapped.
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.
For example, when bootstrapping an application, you can register many initializers using the same token.
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.
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.
### 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.
The following example shows the tree-shakable equivalent to the `ServiceModule` example above.
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.
This page provides a conceptual overview of a dependency injection technique that is recommended for library developers.
Designing your library with *lightweight injection tokens* helps optimize the bundle size of client applications that use your library.
You can manage the dependency structure among your components and injectable services to optimize bundle size by using [tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers).
You can manage the dependency structure among your components and injectable services to optimize bundle size by using [tree-shakable providers](guide/architecture-services#introduction-to-services-and-dependency-injection).
This normally ensures that if a provided component or service is never actually used by the app, the compiler can eliminate its code from the bundle.
However, due to the way Angular stores injection tokens, it is possible that such an unused component or service can end up in the bundle anyway.
@ -89,7 +89,7 @@ These effectively change `constructor(@Optional() other: OtherComponent)` to `co
<divclass="alert is helpful">
For all services, a library should use [tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers), providing dependencies at the root level rather than in component constructors.
For all services, a library should use [tree-shakable providers](guide/architecture-services#introduction-to-services-and-dependency-injection), providing dependencies at the root level rather than in component constructors.