{ "id": "guide/dependency-injection", "title": "Dependency injection in Angular", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Dependency injection in Angularlink

\n

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.

\n

Angular's DI framework provides dependencies to a class upon instantiation.\nYou can use Angular DI to increase flexibility and modularity in your applications.

\n
\n

See the for a working example containing the code snippets in this guide.

\n
\n

Creating an injectable servicelink

\n

To generate a new HeroService class in the src/app/heroes folder use the following Angular CLI command.

\n\nng generate service heroes/hero\n\n

This command creates the following default HeroService.

\n\nimport { Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class HeroService {\n constructor() { }\n}\n\n\n\n

The @Injectable() decorator specifies that Angular can use this class in the DI system.\nThe metadata, providedIn: 'root', means that the HeroService is visible throughout the application.

\n

Next, to get the hero mock data, add a getHeroes() method that returns the heroes from mock.heroes.ts.

\n\nimport { Injectable } from '@angular/core';\nimport { HEROES } from './mock-heroes';\n\n@Injectable({\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\n

For clarity and maintainability, it is recommended that you define components and services in separate files.

\n

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.

\n\n\n

Injecting serviceslink

\n

Injecting services results in making them visible to a component.

\n

To inject a dependency in a component's constructor(), supply a constructor argument with the dependency type.\nThe following example specifies the HeroService in the HeroListComponent constructor.\nThe type of heroService is HeroService.

\n\nconstructor(heroService: HeroService)\n\n\n

For more information, see Providing dependencies in modules and Hierarchical injectors.

\n\n

Using services in other serviceslink

\n

When a service depends on another service, follow the same pattern as injecting into a component.\nIn the following example HeroService depends on a Logger service to report its activities.

\n

First, import the Logger service.\nNext, inject the Logger service in the HeroService constructor() by specifying private logger: Logger within the parentheses.

\n

When you create a class whose constructor() has parameters, specify the type and metadata about those parameters so that Angular can inject the correct service.

\n

Here, the constructor() specifies a type of Logger and stores the instance of Logger in a private field called logger.

\n

The following code tabs feature the Logger service and two versions of HeroService.\nThe first version of HeroService does not depend on the Logger service.\nThe revised second version does depend on Logger service.

\n\n\n \nimport { Injectable } from '@angular/core';\nimport { HEROES } from './mock-heroes';\nimport { Logger } from '../logger.service';\n\n@Injectable({\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\n\n \nimport { Injectable } from '@angular/core';\nimport { HEROES } from './mock-heroes';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class HeroService {\n getHeroes() { return HEROES; }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\n\n@Injectable({\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\n\n\n

In this example, the getHeroes() method uses the Logger service by logging a message when fetching heroes.

\n

What's nextlink

\n\n\n \n
\n\n\n" }