{ "id": "guide/dependency-injection", "title": "Dependency injection in Angular", "contents": "\n\n\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.
\nAngular's DI framework provides dependencies to a class upon instantiation.\nYou can use Angular DI to increase flexibility and modularity in your applications.
\nSee the
To generate a new HeroService
class in the src/app/heroes
folder use the following Angular CLI command.
This command creates the following default HeroService
.
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.
Next, to get the hero mock data, add a getHeroes()
method that returns the heroes from mock.heroes.ts
.
For clarity and maintainability, it is recommended that you define components and services in separate files.
\nIf 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\nInjecting services results in making them visible to a component.
\nTo 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
.
For more information, see Providing dependencies in modules and Hierarchical injectors.
\n\nWhen 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.
First, import the Logger
service.\nNext, inject the Logger
service in the HeroService
constructor()
by specifying private logger: Logger
within the parentheses.
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.
Here, the constructor()
specifies a type of Logger
and stores the instance of Logger
in a private field called logger
.
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.
In this example, the getHeroes()
method uses the Logger
service by logging a message when fetching heroes.