5 lines
79 KiB
JSON
5 lines
79 KiB
JSON
{
|
|
"id": "guide/hierarchical-dependency-injection",
|
|
"title": "Hierarchical injectors",
|
|
"contents": "\n\n\n<div class=\"github-links\">\n <a href=\"https://github.com/angular/angular/edit/master/aio/content/guide/hierarchical-dependency-injection.md?message=docs%3A%20describe%20your%20change...\" aria-label=\"Suggest Edits\" title=\"Suggest Edits\"><i class=\"material-icons\" aria-hidden=\"true\" role=\"img\">mode_edit</i></a>\n</div>\n\n\n<div class=\"content\">\n <h1 id=\"hierarchical-injectors\">Hierarchical injectors<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#hierarchical-injectors\"><i class=\"material-icons\">link</i></a></h1>\n<p>Injectors in Angular have rules that you can leverage to\nachieve the desired visibility of injectables in your apps.\nBy understanding these rules, you can determine in which\nNgModule, Component or Directive you should declare a provider.</p>\n<h2 id=\"two-injector-hierarchies\">Two injector hierarchies<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#two-injector-hierarchies\"><i class=\"material-icons\">link</i></a></h2>\n<p>There are two injector hierarchies in Angular:</p>\n<ol>\n<li><code>ModuleInjector</code> hierarchy—configure a <code>ModuleInjector</code>\nin this hierarchy using an <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code> or <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> annotation.</li>\n<li><code>ElementInjector</code> hierarchy—created implicitly at each\nDOM element. An <code>ElementInjector</code> is empty by default\nunless you configure it in the <code>providers</code> property on\n<code>@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>()</code> or <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code>.</li>\n</ol>\n<a id=\"register-providers-injectable\"></a>\n<h3 id=\"moduleinjector\"><code>ModuleInjector</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#moduleinjector\"><i class=\"material-icons\">link</i></a></h3>\n<p>The <code>ModuleInjector</code> can be configured in one of two ways:</p>\n<ul>\n<li>Using the <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> <code>providedIn</code> property to\nrefer to <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code>, or <code>root</code>.</li>\n<li>Using the <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code> <code>providers</code> array.</li>\n</ul>\n<div class=\"is-helpful alert\">\n<h4 id=\"tree-shaking-and-injectable\">Tree-shaking and <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#tree-shaking-and-injectable\"><i class=\"material-icons\">link</i></a></h4>\n<p>Using the <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> <code>providedIn</code> property is preferable\nto the <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code> <code>providers</code>\narray because with <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> <code>providedIn</code>, optimization\ntools can perform\ntree-shaking, which removes services that your app isn't\nusing and results in smaller bundle sizes.</p>\n<p>Tree-shaking is especially useful for a library\nbecause the application which uses the library may not have\na need to inject it. Read more\nabout <a href=\"guide/architecture-services#providing-services\">tree-shakable providers</a>\nin <a href=\"guide/architecture-services\">Introduction to services and dependency injection</a>.</p>\n</div>\n<p><code>ModuleInjector</code> is configured by the <code>@<a href=\"api/core/NgModule#providers\" class=\"code-anchor\">NgModule.providers</a></code> and\n<code><a href=\"api/core/NgModule#imports\" class=\"code-anchor\">NgModule.imports</a></code> property. <code>ModuleInjector</code> is a flattening of\nall of the providers arrays which can be reached by following the\n<code><a href=\"api/core/NgModule#imports\" class=\"code-anchor\">NgModule.imports</a></code> recursively.</p>\n<p>Child <code>ModuleInjector</code>s are created when lazy loading other <code>@NgModules</code>.</p>\n<p>Provide services with the <code>providedIn</code> property of <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> as follows:</p>\n<code-example language=\"ts\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n providedIn: 'root' // <--provides this service in the root ModuleInjector\n})\nexport class ItemService {\n name = 'telephone';\n}\n</code-example>\n<p>The <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> decorator identifies a service class.\nThe <code>providedIn</code> property configures a specific <code>ModuleInjector</code>,\nhere <code>root</code>, which makes the service available in the <code>root</code> <code>ModuleInjector</code>.</p>\n<h4 id=\"platform-injector\">Platform injector<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#platform-injector\"><i class=\"material-icons\">link</i></a></h4>\n<p>There are two more injectors above <code>root</code>, an\nadditional <code>ModuleInjector</code> and <code>NullInjector()</code>.</p>\n<p>Consider how Angular bootstraps the app with the\nfollowing in <code>main.ts</code>:</p>\n<code-example language=\"javascript\">\n<a href=\"api/platform-browser-dynamic/platformBrowserDynamic\" class=\"code-anchor\">platformBrowserDynamic</a>().bootstrapModule(AppModule).then(ref => {...})\n</code-example>\n<p>The <code>bootstrapModule()</code> method creates a child injector of\nthe platform injector which is configured by the <code>AppModule</code>.\nThis is the <code>root</code> <code>ModuleInjector</code>.</p>\n<p>The <code><a href=\"api/platform-browser-dynamic/platformBrowserDynamic\" class=\"code-anchor\">platformBrowserDynamic</a>()</code> method creates an injector\nconfigured by a <code>PlatformModule</code>, which contains platform-specific\ndependencies. This allows multiple apps to share a platform\nconfiguration.\nFor example, a browser has only one URL bar, no matter how\nmany apps you have running.\nYou can configure additional platform-specific providers at the\nplatform level by supplying <code>extraProviders</code> using the <code><a href=\"api/platform-browser/platformBrowser\" class=\"code-anchor\">platformBrowser</a>()</code> function.</p>\n<p>The next parent injector in the hierarchy is the <code>NullInjector()</code>,\nwhich is the top of the tree. If you've gone so far up the tree\nthat you are looking for a service in the <code>NullInjector()</code>, you'll\nget an error unless you've used <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> because ultimately,\neverything ends at the <code>NullInjector()</code> and it returns an error or,\nin the case of <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code>, <code>null</code>. For more information on\n<code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code>, see the <a href=\"guide/hierarchical-dependency-injection#optional\"><code>@Optional()</code> section</a> of this guide.</p>\n<p>The following diagram represents the relationship between the\n<code>root</code> <code>ModuleInjector</code> and its parent injectors as the\nprevious paragraphs describe.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection/injectors.svg\" alt=\"NullInjector, ModuleInjector, root injector\" width=\"600\" height=\"445\">\n</div>\n<p>While the name <code>root</code> is a special alias, other <code>ModuleInjector</code>s\ndon't have aliases. You have the option to create <code>ModuleInjector</code>s\nwhenever a dynamically loaded component is created, such as with\nthe Router, which will create child <code>ModuleInjector</code>s.</p>\n<p>All requests forward up to the root injector, whether you configured it\nwith the <code>bootstrapModule()</code> method, or registered all providers\nwith <code>root</code> in their own services.</p>\n<div class=\"alert is-helpful\">\n<h4 id=\"injectable-vs-ngmodule\"><code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> vs. <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#injectable-vs-ngmodule\"><i class=\"material-icons\">link</i></a></h4>\n<p>If you configure an app-wide provider in the <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code> of\n<code>AppModule</code>, it overrides one configured for <code>root</code> in the\n<code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> metadata. You can do this to configure a\nnon-default provider of a service that is shared with multiple apps.</p>\n<p>Here is an example of the case where the component router\nconfiguration includes\na non-default <a href=\"guide/router#location-strategy\">location strategy</a>\nby listing its provider\nin the <code>providers</code> list of the <code>AppModule</code>.</p>\n<code-example path=\"dependency-injection-in-action/src/app/app.module.ts\" region=\"providers\" header=\"src/app/app.module.ts (providers)\">\nproviders: [\n { provide: <a href=\"api/common/LocationStrategy\" class=\"code-anchor\">LocationStrategy</a>, useClass: <a href=\"api/common/HashLocationStrategy\" class=\"code-anchor\">HashLocationStrategy</a> }\n]\n\n</code-example>\n</div>\n<h3 id=\"elementinjector\"><code>ElementInjector</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#elementinjector\"><i class=\"material-icons\">link</i></a></h3>\n<p>Angular creates <code>ElementInjector</code>s implicitly for each DOM element.</p>\n<p>Providing a service in the <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> decorator using\nits <code>providers</code> or <code>viewProviders</code>\nproperty configures an <code>ElementInjector</code>.\nFor example, the following <code>TestComponent</code> configures the <code>ElementInjector</code>\nby providing the service as follows:</p>\n<code-example language=\"ts\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n ...\n providers: [{ provide: ItemService, useValue: { name: 'lamp' } }]\n})\nexport class TestComponent\n</code-example>\n<div class=\"alert is-helpful\">\n<p><strong>Note:</strong> Please see the\n<a href=\"guide/hierarchical-dependency-injection#resolution-rules\">resolution rules</a>\nsection to understand the relationship between the <code>ModuleInjector</code> tree and\nthe <code>ElementInjector</code> tree.</p>\n</div>\n<p>When you provide services in a component, that service is available via\nthe <code>ElementInjector</code> at that component instance.\nIt may also be visible at\nchild component/directives based on visibility rules described in the <a href=\"guide/hierarchical-dependency-injection#resolution-rules\">resolution rules</a> section.</p>\n<p>When the component instance is destroyed, so is that service instance.</p>\n<h4 id=\"directive-and-component\"><code>@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>()</code> and <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#directive-and-component\"><i class=\"material-icons\">link</i></a></h4>\n<p>A component is a special type of directive, which means that\njust as <code>@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>()</code> has a <code>providers</code> property, <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> does too.\nThis means that directives as well as components can configure\nproviders, using the <code>providers</code> property.\nWhen you configure a provider for a component or directive\nusing the <code>providers</code> property,\nthat provider belongs to the <code>ElementInjector</code> of that component or\ndirective.\nComponents and directives on the same element share an injector.</p>\n<a id=\"resolution-rules\"></a>\n<h2 id=\"resolution-rules\">Resolution rules<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#resolution-rules\"><i class=\"material-icons\">link</i></a></h2>\n<p>When resolving a token for a component/directive, Angular\nresolves it in two phases:</p>\n<ol>\n<li>Against the <code>ElementInjector</code> hierarchy (its parents)</li>\n<li>Against the <code>ModuleInjector</code> hierarchy (its parents)</li>\n</ol>\n<p>When a component declares a dependency, Angular tries to satisfy that\ndependency with its own <code>ElementInjector</code>.\nIf the component's injector lacks the provider, it passes the request\nup to its parent component's <code>ElementInjector</code>.</p>\n<p>The requests keep forwarding up until Angular finds an injector that can\nhandle the request or runs out of ancestor <code>ElementInjector</code>s.</p>\n<p>If Angular doesn't find the provider in any <code>ElementInjector</code>s,\nit goes back to the element where the request originated and looks\nin the <code>ModuleInjector</code> hierarchy.\nIf Angular still doesn't find the provider, it throws an error.</p>\n<p>If you have registered a provider for the same DI token at\ndifferent levels, the first one Angular encounters is the one\nit uses to resolve the dependency. If, for example, a provider\nis registered locally in the component that needs a service,\nAngular doesn't look for another provider of the same service.</p>\n<h2 id=\"resolution-modifiers\">Resolution modifiers<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#resolution-modifiers\"><i class=\"material-icons\">link</i></a></h2>\n<p>Angular's resolution behavior can be modified with <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code>, <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code>,\n<code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> and <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code>. Import each of them from <code>@angular/core</code>\nand use each in the component class constructor when you inject your service.</p>\n<p>For a working app showcasing the resolution modifiers that\nthis section covers, see the <live-example name=\"resolution-modifiers\">resolution modifiers example</live-example>.</p>\n<h3 id=\"types-of-modifiers\">Types of modifiers<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#types-of-modifiers\"><i class=\"material-icons\">link</i></a></h3>\n<p>Resolution modifiers fall into three categories:</p>\n<ol>\n<li>What to do if Angular doesn't find what you're\nlooking for, that is <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code></li>\n<li>Where to start looking, that is <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code></li>\n<li>Where to stop looking, <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> and <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code></li>\n</ol>\n<p>By default, Angular always starts at the current <code><a href=\"api/core/Injector\" class=\"code-anchor\">Injector</a></code> and keeps\nsearching all the way up. Modifiers allow you to change the starting\n(self) or ending location.</p>\n<p>Additionally, you can combine all of the modifiers except <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> and <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> and of course <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> and <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code>.</p>\n<a id=\"optional\"></a>\n<h3 id=\"optional\"><code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#optional\"><i class=\"material-icons\">link</i></a></h3>\n<p><code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> allows Angular to consider a service you inject to be optional.\nThis way, if it can't be resolved at runtime, Angular simply\nresolves the service as <code>null</code>, rather than throwing an error. In\nthe following example, the service, <code>OptionalService</code>, isn't provided in\nthe service, <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code>, or component class, so it isn't available\nanywhere in the app.</p>\n<code-example path=\"resolution-modifiers/src/app/optional/optional.component.ts\" header=\"resolution-modifiers/src/app/optional/optional.component.ts\" region=\"optional-component\">\nexport class OptionalComponent {\n constructor(@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public optional?: OptionalService) {}\n}\n\n</code-example>\n<h3 id=\"self\"><code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#self\"><i class=\"material-icons\">link</i></a></h3>\n<p>Use <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> so that Angular will only look at the <code>ElementInjector</code> for the current component or directive.</p>\n<p>A good use case for <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> is to inject a service but only if it is\navailable on the current host element. To avoid errors in this situation,\ncombine <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> with <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code>.</p>\n<p>For example, in the following <code>SelfComponent</code>, notice\nthe injected <code>LeafService</code> in\nthe constructor.</p>\n<code-example path=\"resolution-modifiers/src/app/self-no-data/self-no-data.component.ts\" header=\"resolution-modifiers/src/app/self-no-data/self-no-data.component.ts\" region=\"self-no-data-component\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-self-no-data',\n templateUrl: './self-no-data.component.html',\n styleUrls: ['./self-no-data.component.css']\n})\nexport class SelfNoDataComponent {\n constructor(@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>() @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public leaf?: LeafService) { }\n}\n\n\n</code-example>\n<p>In this example, there is a parent provider and injecting the\nservice will return the value, however, injecting the service\nwith <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> and <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> will return <code>null</code> because\n<code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code> tells the injector to stop searching in the current\nhost element.</p>\n<p>Another example shows the component class with a provider\nfor <code>FlowerService</code>. In this case, the injector looks no further\nthan the current <code>ElementInjector</code> because it finds the <code>FlowerService</code> and returns the yellow flower 🌼.</p>\n<code-example path=\"resolution-modifiers/src/app/self/self.component.ts\" header=\"resolution-modifiers/src/app/self/self.component.ts\" region=\"self-component\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-self',\n templateUrl: './self.component.html',\n styleUrls: ['./self.component.css'],\n providers: [{ provide: FlowerService, useValue: { emoji: '🌼' } }]\n\n})\nexport class SelfComponent {\n constructor(@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>() public flower: FlowerService) {}\n}\n\n</code-example>\n<h3 id=\"skipself\"><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#skipself\"><i class=\"material-icons\">link</i></a></h3>\n<p><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> is the opposite of <code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code>. With <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>, Angular\nstarts its search for a service in the parent <code>ElementInjector</code>, rather than\nin the current one. So if the parent <code>ElementInjector</code> were using the value <code>🌿</code> (fern)\nfor <code>emoji</code> , but you had <code>🍁</code> (maple leaf) in the component's <code>providers</code> array,\nAngular would ignore <code>🍁</code> (maple leaf) and use <code>🌿</code> (fern).</p>\n<p>To see this in code, assume that the following value for <code>emoji</code> is what the parent component were using, as in this service:</p>\n<code-example path=\"resolution-modifiers/src/app/leaf.service.ts\" header=\"resolution-modifiers/src/app/leaf.service.ts\" region=\"leafservice\">\nexport class LeafService {\n emoji = '🌿';\n}\n\n</code-example>\n<p>Imagine that in the child component, you had a different value, <code>🍁</code> (maple leaf) but you wanted to use the parent's value instead. This is when you'd use <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>:</p>\n<code-example path=\"resolution-modifiers/src/app/skipself/skipself.component.ts\" header=\"resolution-modifiers/src/app/skipself/skipself.component.ts\" region=\"skipself-component\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-skipself',\n templateUrl: './skipself.component.html',\n styleUrls: ['./skipself.component.css'],\n // Angular would ignore this LeafService instance\n providers: [{ provide: LeafService, useValue: { emoji: '🍁' } }]\n})\nexport class SkipselfComponent {\n // Use @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() in the constructor\n constructor(@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() public leaf: LeafService) { }\n}\n\n</code-example>\n<p>In this case, the value you'd get for <code>emoji</code> would be <code>🌿</code> (fern), not <code>🍁</code> (maple leaf).</p>\n<h4 id=\"skipself-with-optional\"><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> with <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#skipself-with-optional\"><i class=\"material-icons\">link</i></a></h4>\n<p>Use <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> with <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> to prevent an error if the value is <code>null</code>. In the following example, the <code>Person</code> service is injected in the constructor. <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> tells Angular to skip the current injector and <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> will prevent an error should the <code>Person</code> service be <code>null</code>.</p>\n<code-example language=\"ts\">\nclass Person {\n constructor(@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() parent?: Person) {}\n}\n</code-example>\n<h3 id=\"host\"><code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#host\"><i class=\"material-icons\">link</i></a></h3>\n<p><code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> 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 <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> as follows:</p>\n<code-example path=\"resolution-modifiers/src/app/host/host.component.ts\" header=\"resolution-modifiers/src/app/host/host.component.ts\" region=\"host-component\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-host',\n templateUrl: './host.component.html',\n styleUrls: ['./host.component.css'],\n // provide the service\n providers: [{ provide: FlowerService, useValue: { emoji: '🌼' } }]\n})\nexport class HostComponent {\n // use @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>() in the constructor when injecting the service\n constructor(@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>() @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public flower?: FlowerService) { }\n\n}\n\n</code-example>\n<p>Since <code>HostComponent</code> has <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> in its constructor, no\nmatter what the parent of <code>HostComponent</code> might have as a\n<code>flower.emoji</code> value,\nthe <code>HostComponent</code> will use <code>🌼</code> (yellow flower).</p>\n<h2 id=\"logical-structure-of-the-template\">Logical structure of the template<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#logical-structure-of-the-template\"><i class=\"material-icons\">link</i></a></h2>\n<p>When you provide services in the component class, services are\nvisible within the <code>ElementInjector</code> tree relative to where\nand how you provide those services.</p>\n<p>Understanding the underlying logical structure of the Angular\ntemplate will give you a foundation for configuring services\nand in turn control their visibility.</p>\n<p>Components are used in your templates, as in the following example:</p>\n<code-example>\n<app-root>\n <app-child></app-child>\n</app-root>\n</code-example>\n<div class=\"alert is-helpful\">\n<p><strong>Note:</strong> Usually, you declare the components and their\ntemplates in separate files. For the purposes of understanding\nhow the injection system works, it is useful to look at them\nfrom the point of view of a combined logical tree. The term\nlogical distinguishes it from the render tree (your application\nDOM tree). To mark the locations of where the component\ntemplates are located, this guide uses the <code><#VIEW></code>\npseudo element, which doesn't actually exist in the render tree\nand is present for mental model purposes only.</p>\n</div>\n<p>The following is an example of how the <code><app-root></code> and <code><app-child></code> view trees are combined into a single logical tree:</p>\n<code-example>\n<app-root>\n <#VIEW>\n <app-child>\n <#VIEW>\n ...content goes here...\n </#VIEW>\n </app-child>\n <#VIEW>\n</app-root>\n</code-example>\n<p>Understanding the idea of the <code><#VIEW></code> demarcation is especially significant when you configure services in the component class.</p>\n<h2 id=\"providing-services-in-component\">Providing services in <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#providing-services-in-component\"><i class=\"material-icons\">link</i></a></h2>\n<p>How you provide services via an <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> (or <code>@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>()</code>)\ndecorator determines their visibility. The following sections\ndemonstrate <code>providers</code> and <code>viewProviders</code> along with ways to\nmodify service visibility with <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> and <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code>.</p>\n<p>A component class can provide services in two ways:</p>\n<ol>\n<li>with a <code>providers</code> array</li>\n</ol>\n<code-example language=\"typescript=\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n ...\n providers: [\n {provide: FlowerService, useValue: {emoji: '🌺'}}\n ]\n})\n</code-example>\n<ol start=\"2\">\n<li>with a <code>viewProviders</code> array</li>\n</ol>\n<code-example language=\"typescript=\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n ...\n viewProviders: [\n {provide: AnimalService, useValue: {emoji: '🐶'}}\n ]\n})\n</code-example>\n<p>To understand how the <code>providers</code> and <code>viewProviders</code> influence service\nvisibility differently, the following sections build\na <live-example name=\"providers-viewproviders\"></live-example>\nstep-by-step and compare the use of <code>providers</code> and <code>viewProviders</code>\nin code and a logical tree.</p>\n<div class=\"alert is-helpful\">\n<p><strong>NOTE:</strong> In the logical tree, you'll see <code>@Provide</code>, <code>@<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a></code>, and\n<code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a></code>, which are not real HTML attributes but are here to demonstrate\nwhat is going on under the hood.</p>\n<ul>\n<li><code>@<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(Token)=>Value</code> demonstrates that if <code>Token</code> is injected at\nthis location in the logical tree its value would be <code>Value</code>.</li>\n<li><code>@Provide(Token=Value)</code> demonstrates that there is a declaration of\n<code>Token</code> provider with value <code>Value</code> at this location in the logical tree.</li>\n<li><code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(Token)</code> demonstrates that a fallback <code><a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a></code> injector\nshould be used at this location.</li>\n</ul>\n</div>\n<h3 id=\"example-app-structure\">Example app structure<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#example-app-structure\"><i class=\"material-icons\">link</i></a></h3>\n<p>The example app has a <code>FlowerService</code> provided in <code>root</code> with an <code>emoji</code>\nvalue of <code>🌺</code> (red hibiscus).</p>\n<code-example path=\"providers-viewproviders/src/app/flower.service.ts\" header=\"providers-viewproviders/src/app/flower.service.ts\" region=\"flowerservice\">\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n providedIn: 'root'\n})\nexport class FlowerService {\n emoji = '🌺';\n}\n\n</code-example>\n<p>Consider a simple app with only an <code>AppComponent</code> and a <code>ChildComponent</code>.\nThe most basic rendered view would look like nested HTML elements such as\nthe following:</p>\n<code-example>\n<app-root> <!-- AppComponent selector -->\n <app-child> <!-- ChildComponent selector -->\n </app-child>\n</app-root>\n</code-example>\n<p>However, behind the scenes, Angular uses a logical view\nrepresentation as follows when resolving injection requests:</p>\n<code-example>\n<app-root> <!-- AppComponent selector -->\n <#VIEW>\n <app-child> <!-- ChildComponent selector -->\n <#VIEW>\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>The <code><#VIEW></code> here represents an instance of a template.\nNotice that each component has its own <code><#VIEW></code>.</p>\n<p>Knowledge of this structure can inform how you provide and\ninject your services, and give you complete control of service visibility.</p>\n<p>Now, consider that <code><app-root></code> simply injects the <code>FlowerService</code>:</p>\n<code-example path=\"providers-viewproviders/src/app/app.component.1.ts\" header=\"providers-viewproviders/src/app/app.component.ts\" region=\"injection\">\nexport class AppComponent {\n constructor(public flower: FlowerService) {}\n}\n\n</code-example>\n<p>Add a binding to the <code><app-root></code> template to visualize the result:</p>\n<code-example path=\"providers-viewproviders/src/app/app.component.html\" header=\"providers-viewproviders/src/app/app.component.html\" region=\"binding-flower\">\n<p>Emoji from FlowerService: {{flower.emoji}}</p>\n\n</code-example>\n<p>The output in the view would be:</p>\n<code-example>\nEmoji from FlowerService: 🌺\n</code-example>\n<p>In the logical tree, this would be represented as follows:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService) flower=>\"🌺\">\n <#VIEW>\n <p>Emoji from FlowerService: {{flower.emoji}} (🌺)</p>\n <app-child>\n <#VIEW>\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>When <code><app-root></code> requests the <code>FlowerService</code>, it is the injector's job\nto resolve the <code>FlowerService</code> token. The resolution of the token happens\nin two phases:</p>\n<ol>\n<li>The injector determines the starting location in the logical tree and\nan ending location of the search. The injector begins with the starting\nlocation and looks for the token at each level in the logical tree. If\nthe token is found it is returned.</li>\n<li>If the token is not found, the injector looks for the closest\nparent <code>@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>()</code> to delegate the request to.</li>\n</ol>\n<p>In the example case, the constraints are:</p>\n<ol>\n<li>Start with <code><#VIEW></code> belonging to <code><app-root></code> and end with <code><app-root></code>.</li>\n</ol>\n<ul>\n<li>Normally the starting point for search is at the point\nof injection. However, in this case <code><app-root></code> <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a></code>s\nare special in that they also include their own <code>viewProviders</code>,\nwhich is why the search starts at <code><#VIEW></code> belonging to <code><app-root></code>.\n(This would not be the case for a directive matched at the same location).</li>\n<li>The ending location just happens to be the same as the component\nitself, because it is the topmost component in this application.</li>\n</ul>\n<ol start=\"2\">\n<li>The <code>AppModule</code> acts as the fallback injector when the\ninjection token can't be found in the <code>ElementInjector</code>s.</li>\n</ol>\n<h3 id=\"using-the-providers-array\">Using the <code>providers</code> array<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#using-the-providers-array\"><i class=\"material-icons\">link</i></a></h3>\n<p>Now, in the <code>ChildComponent</code> class, add a provider for <code>FlowerService</code>\nto demonstrate more complex resolution rules in the upcoming sections:</p>\n<code-example path=\"providers-viewproviders/src/app/child/child.component.1.ts\" header=\"providers-viewproviders/src/app/child.component.ts\" region=\"flowerservice\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-child',\n templateUrl: './child.component.html',\n styleUrls: ['./child.component.css'],\n // use the providers array to provide a service\n providers: [{ provide: FlowerService, useValue: { emoji: '🌻' } }]\n})\n\nexport class ChildComponent {\n // inject the service\n constructor( public flower: FlowerService) { }\n}\n\n\n</code-example>\n<p>Now that the <code>FlowerService</code> is provided in the <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> decorator,\nwhen the <code><app-child></code> requests the service, the injector has only to look\nas far as the <code><app-child></code>'s own <code>ElementInjector</code>. It won't have to\ncontinue the search any further through the injector tree.</p>\n<p>The next step is to add a binding to the <code>ChildComponent</code> template.</p>\n<code-example path=\"providers-viewproviders/src/app/child/child.component.html\" header=\"providers-viewproviders/src/app/child.component.html\" region=\"flower-binding\">\n<p>Emoji from FlowerService: {{flower.emoji}}</p>\n\n</code-example>\n<p>To render the new values, add <code><app-child></code> to the bottom of\nthe <code>AppComponent</code> template so the view also displays the sunflower:</p>\n<code-example>\nChild <a href=\"api/core/Component\" class=\"code-anchor\">Component</a>\nEmoji from FlowerService: 🌻\n</code-example>\n<p>In the logical tree, this would be represented as follows:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService) flower=>\"🌺\">\n <#VIEW>\n <p>Emoji from FlowerService: {{flower.emoji}} (🌺)</p>\n <app-child @Provide(FlowerService=\"🌻\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService)=>\"🌻\"> <!-- search ends here -->\n <#VIEW> <!-- search starts here -->\n <h2>Parent <a href=\"api/core/Component\" class=\"code-anchor\">Component</a></h2>\n <p>Emoji from FlowerService: {{flower.emoji}} (🌻)</p>\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>When <code><app-child></code> requests the <code>FlowerService</code>, the injector begins\nits search at the <code><#VIEW></code> belonging to <code><app-child></code> (<code><#VIEW></code> is\nincluded because it is injected from <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code>) and ends with\n<code><app-child></code>. In this case, the <code>FlowerService</code> is resolved in the\n<code><app-child></code>'s <code>providers</code> array with sunflower 🌻. The injector doesn't\nhave to look any further in the injector tree. It stops as soon as it\nfinds the <code>FlowerService</code> and never sees the 🌺 (red hibiscus).</p>\n<a id=\"use-view-providers\"></a>\n<h3 id=\"using-the-viewproviders-array\">Using the <code>viewProviders</code> array<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#using-the-viewproviders-array\"><i class=\"material-icons\">link</i></a></h3>\n<p>Use the <code>viewProviders</code> array as another way to provide services in the\n<code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> decorator. Using <code>viewProviders</code> makes services\nvisible in the <code><#VIEW></code>.</p>\n<div class=\"is-helpful alert\">\n<p>The steps are the same as using the <code>providers</code> array,\nwith the exception of using the <code>viewProviders</code> array instead.</p>\n<p>For step-by-step instructions, continue with this section. If you can\nset it up on your own, skip ahead to <a href=\"guide/hierarchical-dependency-injection#modify-visibility\">Modifying service availability</a>.</p>\n</div>\n<p>The example app features a second service, the <code>AnimalService</code> to\ndemonstrate <code>viewProviders</code>.</p>\n<p>First, create an <code>AnimalService</code> with an <code>emoji</code> property of 🐳 (whale):</p>\n<code-example path=\"providers-viewproviders/src/app/animal.service.ts\" header=\"providers-viewproviders/src/app/animal.service.ts\" region=\"animal-service\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n providedIn: 'root'\n})\nexport class AnimalService {\n emoji = '🐳';\n}\n\n</code-example>\n<p>Following the same pattern as with the <code>FlowerService</code>, inject the\n<code>AnimalService</code> in the <code>AppComponent</code> class:</p>\n<code-example path=\"providers-viewproviders/src/app/app.component.ts\" header=\"providers-viewproviders/src/app/app.component.ts\" region=\"inject-animal-service\">\nexport class AppComponent {\n constructor(public flower: FlowerService, public animal: AnimalService) {}\n}\n\n</code-example>\n<div class=\"alert is-helpful\">\n<p><strong>Note:</strong> You can leave all the <code>FlowerService</code> related code in place\nas it will allow a comparison with the <code>AnimalService</code>.</p>\n</div>\n<p>Add a <code>viewProviders</code> array and inject the <code>AnimalService</code> in the\n<code><app-child></code> class, too, but give <code>emoji</code> a different value. Here,\nit has a value of 🐶 (puppy).</p>\n<code-example path=\"providers-viewproviders/src/app/child/child.component.ts\" header=\"providers-viewproviders/src/app/child.component.ts\" region=\"provide-animal-service\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-child',\n templateUrl: './child.component.html',\n styleUrls: ['./child.component.css'],\n // provide services\n providers: [{ provide: FlowerService, useValue: { emoji: '🌻' } }],\n viewProviders: [{ provide: AnimalService, useValue: { emoji: '🐶' } }]\n})\n\nexport class ChildComponent {\n // inject service\n constructor( public flower: FlowerService, public animal: AnimalService) { }\n}\n\n</code-example>\n<p>Add bindings to the <code>ChildComponent</code> and the <code>AppComponent</code> templates.\nIn the <code>ChildComponent</code> template, add the following binding:</p>\n<code-example path=\"providers-viewproviders/src/app/child/child.component.html\" header=\"providers-viewproviders/src/app/child.component.html\" region=\"animal-binding\">\n<p>Emoji from AnimalService: {{animal.emoji}}</p>\n\n</code-example>\n<p>Additionally, add the same to the <code>AppComponent</code> template:</p>\n<code-example path=\"providers-viewproviders/src/app/app.component.html\" header=\"providers-viewproviders/src/app/app.component.html\" region=\"binding-animal\">\n<p>Emoji from AnimalService: {{animal.emoji}}</p>\n\n</code-example>\n<p>Now you should see both values in the browser:</p>\n<code-example>\nAppComponent\nEmoji from AnimalService: 🐳\n\nChild <a href=\"api/core/Component\" class=\"code-anchor\">Component</a>\nEmoji from AnimalService: 🐶\n</code-example>\n<p>The logic tree for this example of <code>viewProviders</code> is as follows:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService) animal=>\"🐳\">\n <#VIEW>\n <app-child>\n <#VIEW\n @Provide(AnimalService=\"🐶\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService=>\"🐶\")>\n <!-- ^^using viewProviders means AnimalService is available in <#VIEW>-->\n <p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>Just as with the <code>FlowerService</code> example, the <code>AnimalService</code> is provided\nin the <code><app-child></code> <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> decorator. This means that since the\ninjector first looks in the <code>ElementInjector</code> of the component, it finds the\n<code>AnimalService</code> value of 🐶 (puppy). It doesn't need to continue searching the\n<code>ElementInjector</code> tree, nor does it need to search the <code>ModuleInjector</code>.</p>\n<h3 id=\"providers-vs-viewproviders\"><code>providers</code> vs. <code>viewProviders</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#providers-vs-viewproviders\"><i class=\"material-icons\">link</i></a></h3>\n<p>To see the difference between using <code>providers</code> and <code>viewProviders</code>, add\nanother component to the example and call it <code>InspectorComponent</code>.\n<code>InspectorComponent</code> will be a child of the <code>ChildComponent</code>. In\n<code>inspector.component.ts</code>, inject the <code>FlowerService</code> and <code>AnimalService</code> in\nthe constructor:</p>\n<code-example path=\"providers-viewproviders/src/app/inspector/inspector.component.ts\" header=\"providers-viewproviders/src/app/inspector/inspector.component.ts\" region=\"injection\">\nexport class InspectorComponent {\n constructor(public flower: FlowerService, public animal: AnimalService) { }\n}\n\n</code-example>\n<p>You do not need a <code>providers</code> or <code>viewProviders</code> array. Next, in\n<code>inspector.component.html</code>, add the same markup from previous components:</p>\n<code-example path=\"providers-viewproviders/src/app/inspector/inspector.component.html\" header=\"providers-viewproviders/src/app/inspector/inspector.component.html\" region=\"binding\">\n<p>Emoji from FlowerService: {{flower.emoji}}</p>\n<p>Emoji from AnimalService: {{animal.emoji}}</p>\n\n</code-example>\n<p>Remember to add the <code>InspectorComponent</code> to the <code>AppModule</code> <code>declarations</code> array.</p>\n<code-example path=\"providers-viewproviders/src/app/app.module.ts\" header=\"providers-viewproviders/src/app/app.module.ts\" region=\"appmodule\">\n@<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>({\n imports: [ <a href=\"api/platform-browser/BrowserModule\" class=\"code-anchor\">BrowserModule</a>, <a href=\"api/forms/FormsModule\" class=\"code-anchor\">FormsModule</a> ],\n declarations: [ AppComponent, ChildComponent, InspectorComponent ],\n bootstrap: [ AppComponent ],\n providers: []\n})\nexport class AppModule { }\n\n</code-example>\n<p>Next, make sure your <code>child.component.html</code> contains the following:</p>\n<code-example path=\"providers-viewproviders/src/app/child/child.component.html\" header=\"providers-viewproviders/src/app/child/child.component.html\" region=\"child-component\">\n<p>Emoji from FlowerService: {{flower.emoji}}</p>\n<p>Emoji from AnimalService: {{animal.emoji}}</p>\n\n<div class=\"container\">\n <h3>Content projection</h3>\n\t<ng-content></ng-content>\n</div>\n\n<h3>Inside the view</h3>\n<app-inspector></app-inspector>\n\n</code-example>\n<p>The first two lines, with the bindings, are there from previous steps. The\nnew parts are <code><ng-content></code> and <code><app-inspector></code>. <code><ng-content></code> allows\nyou to project content, and <code><app-inspector></code> inside the <code>ChildComponent</code>\ntemplate makes the <code>InspectorComponent</code> a child component of\n<code>ChildComponent</code>.</p>\n<p>Next, add the following to <code>app.component.html</code> to take advantage of content projection.</p>\n<code-example path=\"providers-viewproviders/src/app/app.component.html\" header=\"providers-viewproviders/src/app/app.component.html\" region=\"content-projection\">\n<app-child><app-inspector></app-inspector></app-child>\n\n</code-example>\n<p>The browser now renders the following, omitting the previous examples\nfor brevity:</p>\n<code-example>\n//...Omitting previous examples. The following applies to this section.\n\nContent projection: This is coming from content. Doesn't get to see\npuppy because the puppy is declared inside the view only.\n\nEmoji from FlowerService: 🌻\nEmoji from AnimalService: 🐳\n\nEmoji from FlowerService: 🌻\nEmoji from AnimalService: 🐶\n</code-example>\n<p>These four bindings demonstrate the difference between <code>providers</code>\nand <code>viewProviders</code>. Since the 🐶 (puppy) is declared inside the <#VIEW>,\nit isn't visible to the projected content. Instead, the projected\ncontent sees the 🐳 (whale).</p>\n<p>The next section though, where <code>InspectorComponent</code> is a child component\nof <code>ChildComponent</code>, <code>InspectorComponent</code> is inside the <code><#VIEW></code>, so\nwhen it asks for the <code>AnimalService</code>, it sees the 🐶 (puppy).</p>\n<p>The <code>AnimalService</code> in the logical tree would look like this:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService) animal=>\"🐳\">\n <#VIEW>\n <app-child>\n <#VIEW\n @Provide(AnimalService=\"🐶\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService=>\"🐶\")>\n <!-- ^^using viewProviders means AnimalService is available in <#VIEW>-->\n <p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>\n <app-inspector>\n <p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>\n </app-inspector>\n </#VIEW>\n <app-inspector>\n <#VIEW>\n <p>Emoji from AnimalService: {{animal.emoji}} (🐳)</p>\n </#VIEW>\n </app-inspector>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>The projected content of <code><app-inspector></code> sees the 🐳 (whale), not\nthe 🐶 (puppy), because the\n🐶 (puppy) is inside the <code><app-child></code> <code><#VIEW></code>. The <code><app-inspector></code> can\nonly see the 🐶 (puppy)\nif it is also within the <code><#VIEW></code>.</p>\n<a id=\"modify-visibility\"></a>\n<h2 id=\"modifying-service-visibility\">Modifying service visibility<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#modifying-service-visibility\"><i class=\"material-icons\">link</i></a></h2>\n<p>This section describes how to limit the scope of the beginning and\nending <code>ElementInjector</code> using the visibility decorators <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code>,\n<code>@<a href=\"api/core/Self\" class=\"code-anchor\">Self</a>()</code>, and <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>.</p>\n<h3 id=\"visibility-of-provided-tokens\">Visibility of provided tokens<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#visibility-of-provided-tokens\"><i class=\"material-icons\">link</i></a></h3>\n<p>Visibility decorators influence where the search for the injection\ntoken begins and ends in the logic tree. To do this, place\nvisibility decorators at the point of injection, that is, the\n<code>constructor()</code>, rather than at a point of declaration.</p>\n<p>To alter where the injector starts looking for <code>FlowerService</code>, add\n<code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> to the <code><app-child></code> <code>@<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a></code> declaration for the\n<code>FlowerService</code>. This declaration is in the <code><app-child></code> constructor\nas shown in <code>child.component.ts</code>:</p>\n<code-example language=\"typescript=\">\n constructor(@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() public flower : FlowerService) { }\n</code-example>\n<p>With <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>, the <code><app-child></code> injector doesn't look to itself for\nthe <code>FlowerService</code>. Instead, the injector starts looking for the\n<code>FlowerService</code> at the <code><app-root></code>'s <code>ElementInjector</code>, where it finds\nnothing. Then, it goes back to the <code><app-child></code> <code>ModuleInjector</code> and finds\nthe 🌺 (red hibiscus) value, which is available because the <code><app-child></code>\n<code>ModuleInjector</code> and the <code><app-root></code> <code>ModuleInjector</code> are flattened into one\n<code>ModuleInjector</code>. Thus, the UI renders the following:</p>\n<code-example>\nEmoji from FlowerService: 🌺\n</code-example>\n<p>In a logical tree, this same idea might look like this:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService) flower=>\"🌺\">\n <#VIEW>\n <app-child @Provide(FlowerService=\"🌻\")>\n <#VIEW @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService, <a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>)=>\"🌺\">\n <!-- With <a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>, the injector looks to the next injector up the tree -->\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p>Though <code><app-child></code> provides the 🌻 (sunflower), the app renders\nthe 🌺 (red hibiscus) because <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> causes the current\ninjector to skip\nitself and look to its parent.</p>\n<p>If you now add <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> (in addition to the <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>) to the\n<code>@<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a></code> of the <code>FlowerService</code>, the result will be <code>null</code>. This is\nbecause <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> limits the upper bound of the search to the\n<code><#VIEW></code>. Here's the idea in the logical tree:</p>\n<code-example>\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService) flower=>\"🌺\">\n <#VIEW> <!-- end search here with null-->\n <app-child @Provide(FlowerService=\"🌻\")> <!-- start search here -->\n <#VIEW @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(FlowerService, @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>, @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>, @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>)=>null>\n </#VIEW>\n </app-parent>\n </#VIEW>\n</app-root>\n</code-example>\n<p>Here, the services and their values are the same, but <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code>\nstops the injector from looking any further than the <code><#VIEW></code>\nfor <code>FlowerService</code>, so it doesn't find it and returns <code>null</code>.</p>\n<div class=\"alert is-helpful\">\n<p><strong>Note:</strong> The example app uses <code>@<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>()</code> so the app does\nnot throw an error, but the principles are the same.</p>\n</div>\n<h3 id=\"skipself-and-viewproviders\"><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> and <code>viewProviders</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#skipself-and-viewproviders\"><i class=\"material-icons\">link</i></a></h3>\n<p>The <code><app-child></code> currently provides the <code>AnimalService</code> in\nthe <code>viewProviders</code> array with the value of 🐶 (puppy). Because\nthe injector has only to look at the <code><app-child></code>'s <code>ElementInjector</code>\nfor the <code>AnimalService</code>, it never sees the 🐳 (whale).</p>\n<p>Just as in the <code>FlowerService</code> example, if you add <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>\nto the constructor for the <code>AnimalService</code>, the injector won't\nlook in the current <code><app-child></code>'s <code>ElementInjector</code> for the\n<code>AnimalService</code>.</p>\n<code-example language=\"typescript=\">\nexport class ChildComponent {\n\n// add @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()\n constructor(@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() public animal : AnimalService) { }\n\n}\n</code-example>\n<p>Instead, the injector will begin at the <code><app-root></code>\n<code>ElementInjector</code>. Remember that the <code><app-child></code> class\nprovides the <code>AnimalService</code> in the <code>viewProviders</code> array\nwith a value of 🐶 (puppy):</p>\n<code-example language=\"ts\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-child',\n ...\n viewProviders:\n [{ provide: AnimalService, useValue: { emoji: '🐶' } }]\n})\n</code-example>\n<p>The logical tree looks like this with <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> in <code><app-child></code>:</p>\n<code-example>\n <app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService=>\"🐳\")>\n <#VIEW><!-- search begins here -->\n <app-child>\n <#VIEW\n @Provide(AnimalService=\"🐶\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService, <a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>=>\"🐳\")>\n <!--Add @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a> -->\n </#VIEW>\n </app-child>\n </#VIEW>\n </app-root>\n</code-example>\n<p>With <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> in the <code><app-child></code>, the injector begins its\nsearch for the <code>AnimalService</code> in the <code><app-root></code> <code>ElementInjector</code>\nand finds 🐳 (whale).</p>\n<h3 id=\"host-and-viewproviders\"><code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> and <code>viewProviders</code><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#host-and-viewproviders\"><i class=\"material-icons\">link</i></a></h3>\n<p>If you add <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> to the constructor for <code>AnimalService</code>, the\nresult is 🐶 (puppy) because the injector finds the <code>AnimalService</code>\nin the <code><app-child></code> <code><#VIEW></code>. Here is the <code>viewProviders</code> array\nin the <code><app-child></code> class and <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> in the constructor:</p>\n<code-example language=\"typescript=\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-child',\n ...\n viewProviders:\n [{ provide: AnimalService, useValue: { emoji: '🐶' } }]\n\n})\nexport class ChildComponent {\n constructor(@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>() public animal : AnimalService) { }\n}\n</code-example>\n<p><code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> causes the injector to look until it encounters the edge of the <code><#VIEW></code>.</p>\n<code-example>\n <app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService=>\"🐳\")>\n <#VIEW>\n <app-child>\n <#VIEW\n @Provide(AnimalService=\"🐶\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService, @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>=>\"🐶\")> <!-- @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a> stops search here -->\n </#VIEW>\n </app-child>\n </#VIEW>\n </app-root>\n</code-example>\n<p>Add a <code>viewProviders</code> array with a third animal, 🦔 (hedgehog), to the\n<code>app.component.ts</code> <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> metadata:</p>\n<code-example language=\"typescript\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: [ './app.component.css' ],\n viewProviders: [{ provide: AnimalService, useValue: { emoji: '🦔' } }]\n})\n</code-example>\n<p>Next, add <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> along with <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> to the constructor for the\n<code>Animal Service</code> in <code>child.component.ts</code>. Here are <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code>\nand <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> in the <code><app-child></code>\nconstructor :</p>\n<code-example language=\"ts\">\nexport class ChildComponent {\n\n constructor(\n @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>() @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() public animal : AnimalService) { }\n\n}\n</code-example>\n<p>When <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> and <code><a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> were applied to the <code>FlowerService</code>,\nwhich is in the <code>providers</code> array, the result was <code>null</code> because\n<code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code> starts its search in the <code><app-child></code> injector, but\n<code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> stops searching at <code><#VIEW></code>—where there is no\n<code>FlowerService</code>. In the logical tree, you can see that the\n<code>FlowerService</code> is visible in <code><app-child></code>, not its <code><#VIEW></code>.</p>\n<p>However, the <code>AnimalService</code>, which is provided in the\n<code>AppComponent</code> <code>viewProviders</code> array, is visible.</p>\n<p>The logical tree representation shows why this is:</p>\n<code-example language=\"html\">\n<app-root @<a href=\"api/core/NgModule\" class=\"code-anchor\">NgModule</a>(AppModule)\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService=>\"🐳\")>\n <#VIEW @Provide(AnimalService=\"🦔\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService, @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>, @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>, @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>)=>\"🦔\">\n <!-- ^^@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() starts here, @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>() stops here^^ -->\n <app-child>\n <#VIEW @Provide(AnimalService=\"🐶\")\n @<a href=\"api/core/Inject\" class=\"code-anchor\">Inject</a>(AnimalService, @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>, @<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>, @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>)=>\"🐶\">\n <!-- Add @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a> ^^-->\n </#VIEW>\n </app-child>\n </#VIEW>\n</app-root>\n</code-example>\n<p><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>()</code>, causes the injector to start its search for\nthe <code>AnimalService</code> at the <code><app-root></code>, not the <code><app-child></code>,\nwhere the request originates, and <code>@<a href=\"api/core/Host\" class=\"code-anchor\">Host</a>()</code> stops the search\nat the <code><app-root></code> <code><#VIEW></code>. Since <code>AnimalService</code> is\nprovided via the <code>viewProviders</code> array, the injector finds 🦔\n(hedgehog) in the <code><#VIEW></code>.</p>\n<a id=\"component-injectors\"></a>\n<h2 id=\"elementinjector-use-case-examples\"><code>ElementInjector</code> use case examples<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#elementinjector-use-case-examples\"><i class=\"material-icons\">link</i></a></h2>\n<p>The ability to configure one or more providers at different levels\nopens up useful possibilities.\nFor a look at the following scenarios in a working app, see the <live-example>heroes use case examples</live-example>.</p>\n<h3 id=\"scenario-service-isolation\">Scenario: service isolation<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#scenario-service-isolation\"><i class=\"material-icons\">link</i></a></h3>\n<p>Architectural reasons may lead you to restrict access to a service to the application domain where it belongs.\nFor example, the guide sample includes a <code>VillainsListComponent</code> that displays a list of villains.\nIt gets those villains from a <code>VillainsService</code>.</p>\n<p>If you provided <code>VillainsService</code> in the root <code>AppModule</code>\n(where you registered the <code>HeroesService</code>),\nthat would make the <code>VillainsService</code> visible everywhere in the\napplication, including the <em>Hero</em> workflows. If you later\nmodified the <code>VillainsService</code>, you could break something in a\nhero component somewhere.</p>\n<p>Instead, you can provide the <code>VillainsService</code> in the <code>providers</code> metadata of the <code>VillainsListComponent</code> like this:</p>\n<code-example path=\"hierarchical-dependency-injection/src/app/villains-list.component.ts\" header=\"src/app/villains-list.component.ts (metadata)\" region=\"metadata\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-villains-list',\n templateUrl: './villains-list.component.html',\n providers: [ VillainsService ]\n})\n\n</code-example>\n<p>By providing <code>VillainsService</code> in the <code>VillainsListComponent</code> metadata and nowhere else,\nthe service becomes available only in the <code>VillainsListComponent</code> and its sub-component tree.</p>\n<p><code>VillainService</code> is a singleton with respect to <code>VillainsListComponent</code>\nbecause that is where it is declared. As long as <code>VillainsListComponent</code>\ndoes not get destroyed it will be the same instance of <code>VillainService</code>\nbut if there are multilple instances of <code>VillainsListComponent</code>, then each\ninstance of <code>VillainsListComponent</code> will have its own instance of <code>VillainService</code>.</p>\n<h3 id=\"scenario-multiple-edit-sessions\">Scenario: multiple edit sessions<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#scenario-multiple-edit-sessions\"><i class=\"material-icons\">link</i></a></h3>\n<p>Many applications allow users to work on several open tasks at the same time.\nFor example, in a tax preparation application, the preparer could be working on several tax returns,\nswitching from one to the other throughout the day.</p>\n<p>This guide demonstrates that scenario with an example in the Tour of Heroes theme.\nImagine an outer <code>HeroListComponent</code> that displays a list of super heroes.</p>\n<p>To open a hero's tax return, the preparer clicks on a hero name, which opens a component for editing that return.\nEach selected hero tax return opens in its own component and multiple returns can be open at the same time.</p>\n<p>Each tax return component has the following characteristics:</p>\n<ul>\n<li>Is its own tax return editing session.</li>\n<li>Can change a tax return without affecting a return in another component.</li>\n<li>Has the ability to save the changes to its tax return or cancel them.</li>\n</ul>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection/hid-heroes-anim.gif\" alt=\"Heroes in action\" width=\"500\" height=\"384\">\n</div>\n<p>Suppose that the <code>HeroTaxReturnComponent</code> had logic to manage and restore changes.\nThat would be a pretty easy task for a simple hero tax return.\nIn the real world, with a rich tax return data model, the change management would be tricky.\nYou could delegate that management to a helper service, as this example does.</p>\n<p>The <code>HeroTaxReturnService</code> caches a single <code>HeroTaxReturn</code>, tracks changes to that return, and can save or restore it.\nIt also delegates to the application-wide singleton <code>HeroService</code>, which it gets by injection.</p>\n<code-example path=\"hierarchical-dependency-injection/src/app/hero-tax-return.service.ts\" header=\"src/app/hero-tax-return.service.ts\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\nimport { HeroTaxReturn } from './hero';\nimport { HeroesService } from './heroes.service';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()\nexport class HeroTaxReturnService {\n private currentTaxReturn: HeroTaxReturn;\n private originalTaxReturn: HeroTaxReturn;\n\n constructor(private heroService: HeroesService) { }\n\n set taxReturn(htr: HeroTaxReturn) {\n this.originalTaxReturn = htr;\n this.currentTaxReturn = htr.clone();\n }\n\n get taxReturn(): HeroTaxReturn {\n return this.currentTaxReturn;\n }\n\n restoreTaxReturn() {\n this.taxReturn = this.originalTaxReturn;\n }\n\n saveTaxReturn() {\n this.taxReturn = this.currentTaxReturn;\n this.heroService.saveTaxReturn(this.currentTaxReturn).subscribe();\n }\n}\n\n\n</code-example>\n<p>Here is the <code>HeroTaxReturnComponent</code> that makes use of <code>HeroTaxReturnService</code>.</p>\n<code-example path=\"hierarchical-dependency-injection/src/app/hero-tax-return.component.ts\" header=\"src/app/hero-tax-return.component.ts\">\nimport { <a href=\"api/core/Component\" class=\"code-anchor\">Component</a>, <a href=\"api/core/EventEmitter\" class=\"code-anchor\">EventEmitter</a>, <a href=\"api/core/Input\" class=\"code-anchor\">Input</a>, <a href=\"api/core/Output\" class=\"code-anchor\">Output</a> } from '@angular/core';\nimport { HeroTaxReturn } from './hero';\nimport { HeroTaxReturnService } from './hero-tax-return.service';\n\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-hero-tax-return',\n templateUrl: './hero-tax-return.component.html',\n styleUrls: [ './hero-tax-return.component.css' ],\n providers: [ HeroTaxReturnService ]\n})\nexport class HeroTaxReturnComponent {\n message = '';\n\n @<a href=\"api/core/Output\" class=\"code-anchor\">Output</a>() close = new <a href=\"api/core/EventEmitter\" class=\"code-anchor\">EventEmitter</a><void>();\n\n get taxReturn(): HeroTaxReturn {\n return this.heroTaxReturnService.taxReturn;\n }\n\n @<a href=\"api/core/Input\" class=\"code-anchor\">Input</a>()\n set taxReturn(htr: HeroTaxReturn) {\n this.heroTaxReturnService.taxReturn = htr;\n }\n\n constructor(private heroTaxReturnService: HeroTaxReturnService) { }\n\n onCanceled() {\n this.flashMessage('Canceled');\n this.heroTaxReturnService.restoreTaxReturn();\n }\n\n onClose() { this.close.emit(); }\n\n onSaved() {\n this.flashMessage('Saved');\n this.heroTaxReturnService.saveTaxReturn();\n }\n\n flashMessage(msg: string) {\n this.message = msg;\n setTimeout(() => this.message = '', 500);\n }\n}\n\n\n</code-example>\n<p>The <em>tax-return-to-edit</em> arrives via the <code>@<a href=\"api/core/Input\" class=\"code-anchor\">Input</a>()</code> property, which is implemented with getters and setters.\nThe setter initializes the component's own instance of the <code>HeroTaxReturnService</code> with the incoming return.\nThe getter always returns what that service says is the current state of the hero.\nThe component also asks the service to save and restore this tax return.</p>\n<p>This won't work if the service is an application-wide singleton.\nEvery component would share the same service instance, and each component would overwrite the tax return that belonged to another hero.</p>\n<p>To prevent this, configure the component-level injector of <code>HeroTaxReturnComponent</code> to provide the service, using the <code>providers</code> property in the component metadata.</p>\n<code-example path=\"hierarchical-dependency-injection/src/app/hero-tax-return.component.ts\" header=\"src/app/hero-tax-return.component.ts (providers)\" region=\"providers\">\nproviders: [ HeroTaxReturnService ]\n\n</code-example>\n<p>The <code>HeroTaxReturnComponent</code> has its own provider of the <code>HeroTaxReturnService</code>.\nRecall that every component <em>instance</em> has its own injector.\nProviding the service at the component level ensures that <em>every</em> instance of the component gets its own, private instance of the service, and no tax return gets overwritten.</p>\n<div class=\"alert is-helpful\">\n<p>The rest of the scenario code relies on other Angular features and techniques that you can learn about elsewhere in the documentation.\nYou can review it and download it from the <live-example></live-example>.</p>\n</div>\n<h3 id=\"scenario-specialized-providers\">Scenario: specialized providers<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#scenario-specialized-providers\"><i class=\"material-icons\">link</i></a></h3>\n<p>Another reason to re-provide a service at another level is to substitute a <em>more specialized</em> implementation of that service, deeper in the component tree.</p>\n<p>Consider a Car component that depends on several services.\nSuppose you configured the root injector (marked as A) with <em>generic</em> providers for\n<code>CarService</code>, <code>EngineService</code> and <code>TiresService</code>.</p>\n<p>You create a car component (A) that displays a car constructed from these three generic services.</p>\n<p>Then you create a child component (B) that defines its own, <em>specialized</em> providers for <code>CarService</code> and <code>EngineService</code>\nthat have special capabilities suitable for whatever is going on in component (B).</p>\n<p>Component (B) is the parent of another component (C) that defines its own, even <em>more specialized</em> provider for <code>CarService</code>.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection/car-components.png\" alt=\"car components\" width=\"338\" height=\"201\">\n</div>\n<p>Behind the scenes, each component sets up its own injector with zero, one, or more providers defined for that component itself.</p>\n<p>When you resolve an instance of <code>Car</code> at the deepest component (C),\nits injector produces an instance of <code>Car</code> resolved by injector (C) with an <code>Engine</code> resolved by injector (B) and\n<code>Tires</code> resolved by the root injector (A).</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection/injector-tree.png\" alt=\"car injector tree\" width=\"600\" height=\"248\">\n</div>\n<h2 id=\"more-on-dependency-injection\">More on dependency injection<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/hierarchical-dependency-injection#more-on-dependency-injection\"><i class=\"material-icons\">link</i></a></h2>\n<p>For more information on Angular dependency injection, see the <a href=\"guide/dependency-injection-providers\">DI Providers</a> and <a href=\"guide/dependency-injection-in-action\">DI in Action</a> guides.</p>\n\n \n</div>\n\n<!-- links to this doc:\n - errors/NG0200\n - guide/dependency-injection\n - guide/dependency-injection-navtree\n - guide/example-apps-list\n - guide/glossary\n - guide/providers\n - guide/template-expression-operators\n - guide/upgrade\n-->\n<!-- links from this doc:\n - api/common/HashLocationStrategy\n - api/common/LocationStrategy\n - api/core/Component\n - api/core/Directive\n - api/core/EventEmitter\n - api/core/Host\n - api/core/Inject\n - api/core/Injectable\n - api/core/Injector\n - api/core/Input\n - api/core/NgModule\n - api/core/NgModule#imports\n - api/core/NgModule#providers\n - api/core/Optional\n - api/core/Output\n - api/core/Self\n - api/core/SkipSelf\n - api/forms/FormsModule\n - api/platform-browser-dynamic/platformBrowserDynamic\n - api/platform-browser/BrowserModule\n - api/platform-browser/platformBrowser\n - guide/architecture-services\n - guide/architecture-services#providing-services\n - guide/dependency-injection-in-action\n - guide/dependency-injection-providers\n - guide/hierarchical-dependency-injection#directive-and-component\n - guide/hierarchical-dependency-injection#elementinjector\n - guide/hierarchical-dependency-injection#elementinjector-use-case-examples\n - guide/hierarchical-dependency-injection#example-app-structure\n - guide/hierarchical-dependency-injection#hierarchical-injectors\n - guide/hierarchical-dependency-injection#host\n - guide/hierarchical-dependency-injection#host-and-viewproviders\n - guide/hierarchical-dependency-injection#injectable-vs-ngmodule\n - guide/hierarchical-dependency-injection#logical-structure-of-the-template\n - guide/hierarchical-dependency-injection#modify-visibility\n - guide/hierarchical-dependency-injection#modifying-service-visibility\n - guide/hierarchical-dependency-injection#moduleinjector\n - guide/hierarchical-dependency-injection#more-on-dependency-injection\n - guide/hierarchical-dependency-injection#optional\n - guide/hierarchical-dependency-injection#platform-injector\n - guide/hierarchical-dependency-injection#providers-vs-viewproviders\n - guide/hierarchical-dependency-injection#providing-services-in-component\n - guide/hierarchical-dependency-injection#resolution-modifiers\n - guide/hierarchical-dependency-injection#resolution-rules\n - guide/hierarchical-dependency-injection#scenario-multiple-edit-sessions\n - guide/hierarchical-dependency-injection#scenario-service-isolation\n - guide/hierarchical-dependency-injection#scenario-specialized-providers\n - guide/hierarchical-dependency-injection#self\n - guide/hierarchical-dependency-injection#skipself\n - guide/hierarchical-dependency-injection#skipself-and-viewproviders\n - guide/hierarchical-dependency-injection#skipself-with-optional\n - guide/hierarchical-dependency-injection#tree-shaking-and-injectable\n - guide/hierarchical-dependency-injection#two-injector-hierarchies\n - guide/hierarchical-dependency-injection#types-of-modifiers\n - guide/hierarchical-dependency-injection#using-the-providers-array\n - guide/hierarchical-dependency-injection#using-the-viewproviders-array\n - guide/hierarchical-dependency-injection#visibility-of-provided-tokens\n - guide/router#location-strategy\n - https://github.com/angular/angular/edit/master/aio/content/guide/hierarchical-dependency-injection.md?message=docs%3A%20describe%20your%20change...\n-->"
|
|
} |