angular-cn/aio/dist/generated/docs/guide/dependency-injection.json

5 lines
9.6 KiB
JSON

{
"id": "guide/dependency-injection",
"title": "Dependency injection in Angular",
"contents": "\n\n\n<div class=\"github-links\">\n <a href=\"https://github.com/angular/angular/edit/master/aio/content/guide/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=\"dependency-injection-in-angular\">Dependency injection in Angular<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection#dependency-injection-in-angular\"><i class=\"material-icons\">link</i></a></h1>\n<p>Dependencies are services or objects that a class needs to perform its function.\nDependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them.</p>\n<p>Angular's DI framework provides dependencies to a class upon instantiation.\nYou can use Angular DI to increase flexibility and modularity in your applications.</p>\n<div class=\"alert is-helpful\">\n<p>See the <live-example></live-example> for a working example containing the code snippets in this guide.</p>\n</div>\n<h2 id=\"creating-an-injectable-service\">Creating an injectable service<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection#creating-an-injectable-service\"><i class=\"material-icons\">link</i></a></h2>\n<p>To generate a new <code>HeroService</code> class in the <code>src/app/heroes</code> folder use the following <a href=\"cli\">Angular CLI</a> command.</p>\n<code-example language=\"sh\" class=\"code-shell\">\nng generate service heroes/hero\n</code-example>\n<p>This command creates the following default <code>HeroService</code>.</p>\n<code-example path=\"dependency-injection/src/app/heroes/hero.service.0.ts\" header=\"src/app/heroes/hero.service.ts (CLI-generated)\">\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 HeroService {\n constructor() { }\n}\n\n\n</code-example>\n<p>The <code>@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>()</code> decorator specifies that Angular can use this class in the DI system.\nThe metadata, <code>providedIn: 'root'</code>, means that the <code>HeroService</code> is visible throughout the application.</p>\n<p>Next, to get the hero mock data, add a <code>getHeroes()</code> method that returns the heroes from <code>mock.heroes.ts</code>.</p>\n<code-example path=\"dependency-injection/src/app/heroes/hero.service.3.ts\" header=\"src/app/heroes/hero.service.ts\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\nimport { HEROES } from './mock-heroes';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n // declares that this service should be created\n // by the root application injector.\n providedIn: 'root',\n})\nexport class HeroService {\n getHeroes() { return HEROES; }\n}\n\n\n</code-example>\n<p>For clarity and maintainability, it is recommended that you define components and services in separate files.</p>\n<p>If you do combine a component and service in the same file, it is important to define the service first, and then the component.\nIf you define the component before the service, Angular returns a run-time null reference error.</p>\n<a id=\"injector-config\"></a>\n<a id=\"bootstrap\"></a>\n<h2 id=\"injecting-services\">Injecting services<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection#injecting-services\"><i class=\"material-icons\">link</i></a></h2>\n<p>Injecting services results in making them visible to a component.</p>\n<p>To inject a dependency in a component's <code>constructor()</code>, supply a constructor argument with the dependency type.\nThe following example specifies the <code>HeroService</code> in the <code>HeroListComponent</code> constructor.\nThe type of <code>heroService</code> is <code>HeroService</code>.</p>\n<code-example header=\"src/app/heroes/hero-list.component (constructor signature)\" path=\"dependency-injection/src/app/heroes/hero-list.component.ts\" region=\"ctor-signature\">\nconstructor(heroService: HeroService)\n\n</code-example>\n<p>For more information, see <a href=\"guide/providers\">Providing dependencies in modules</a> and <a href=\"guide/hierarchical-dependency-injection\">Hierarchical injectors</a>.</p>\n<a id=\"service-needs-service\"></a>\n<h2 id=\"using-services-in-other-services\">Using services in other services<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection#using-services-in-other-services\"><i class=\"material-icons\">link</i></a></h2>\n<p>When a service depends on another service, follow the same pattern as injecting into a component.\nIn the following example <code>HeroService</code> depends on a <code>Logger</code> service to report its activities.</p>\n<p>First, import the <code>Logger</code> service.\nNext, inject the <code>Logger</code> service in the <code>HeroService</code> <code>constructor()</code> by specifying <code>private logger: Logger</code> within the parentheses.</p>\n<p>When you create a class whose <code>constructor()</code> has parameters, specify the type and metadata about those parameters so that Angular can inject the correct service.</p>\n<p>Here, the <code>constructor()</code> specifies a type of <code>Logger</code> and stores the instance of <code>Logger</code> in a private field called <code>logger</code>.</p>\n<p>The following code tabs feature the <code>Logger</code> service and two versions of <code>HeroService</code>.\nThe first version of <code>HeroService</code> does not depend on the <code>Logger</code> service.\nThe revised second version does depend on <code>Logger</code> service.</p>\n<code-tabs>\n\n <code-pane header=\"src/app/heroes/hero.service (v2)\" path=\"dependency-injection/src/app/heroes/hero.service.2.ts\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\nimport { HEROES } from './mock-heroes';\nimport { Logger } from '../logger.service';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n providedIn: 'root',\n})\nexport class HeroService {\n\n constructor(private logger: Logger) { }\n\n getHeroes() {\n this.logger.log('Getting heroes ...');\n return HEROES;\n }\n}\n\n\n</code-pane>\n\n <code-pane header=\"src/app/heroes/hero.service (v1)\" path=\"dependency-injection/src/app/heroes/hero.service.1.ts\">\nimport { <a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a> } from '@angular/core';\nimport { HEROES } from './mock-heroes';\n\n@<a href=\"api/core/Injectable\" class=\"code-anchor\">Injectable</a>({\n providedIn: 'root',\n})\nexport class HeroService {\n getHeroes() { return HEROES; }\n}\n\n\n</code-pane>\n\n <code-pane header=\"src/app/logger.service\" path=\"dependency-injection/src/app/logger.service.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'\n})\nexport class Logger {\n logs: string[] = []; // capture logs for testing\n\n log(message: string) {\n this.logs.push(message);\n console.log(message);\n }\n}\n\n\n</code-pane>\n\n</code-tabs>\n<p>In this example, the <code>getHeroes()</code> method uses the <code>Logger</code> service by logging a message when fetching heroes.</p>\n<h2 id=\"whats-next\">What's next<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection#whats-next\"><i class=\"material-icons\">link</i></a></h2>\n<ul>\n<li><a href=\"guide/dependency-injection-providers\">Dependency providers</a></li>\n<li><a href=\"guide/dependency-injection-providers\">DI tokens and providers</a></li>\n<li><a href=\"guide/dependency-injection-in-action\">Dependency Injection in Action</a></li>\n</ul>\n\n \n</div>\n\n<!-- links to this doc:\n - api/core/ClassProvider\n - api/core/ClassSansProvider\n - api/core/ConstructorProvider\n - api/core/ConstructorSansProvider\n - api/core/ExistingProvider\n - api/core/ExistingSansProvider\n - api/core/FactoryProvider\n - api/core/FactorySansProvider\n - api/core/Inject\n - api/core/Injectable\n - api/core/Optional\n - api/core/Provider\n - api/core/StaticClassProvider\n - api/core/TypeProvider\n - api/core/ValueProvider\n - errors/NG0201\n - guide/architecture-next-steps\n - guide/architecture-services\n - guide/attribute-binding\n - guide/attribute-directives\n - guide/docs-style-guide\n - guide/example-apps-list\n - guide/glossary\n - guide/http\n - guide/ngmodule-api\n - guide/router\n - guide/sharing-ngmodules\n - guide/testing-services\n - guide/upgrade\n - guide/what-is-angular\n - tutorial/toh-pt4\n-->\n<!-- links from this doc:\n - api/core/Injectable\n - cli\n - guide/dependency-injection#creating-an-injectable-service\n - guide/dependency-injection#dependency-injection-in-angular\n - guide/dependency-injection#injecting-services\n - guide/dependency-injection#using-services-in-other-services\n - guide/dependency-injection#whats-next\n - guide/dependency-injection-in-action\n - guide/dependency-injection-providers\n - guide/hierarchical-dependency-injection\n - guide/providers\n - https://github.com/angular/angular/edit/master/aio/content/guide/dependency-injection.md?message=docs%3A%20describe%20your%20change...\n-->"
}