Dependency Injection

Dependency injection (DI) provides Components with access to Services and other resources. Angular provides the ability for you to inject a service into a component to give that component access to the service.

  • The injector is the main mechanism. Angular creates an application-wide injector for you during the bootstrap process, and additional injectors as needed. You don't have to create injectors.
  • An injector creates dependencies and maintains a container of dependency instances that it reuses, if possible.
  • A provider is an object that tells an injector how to obtain or create a dependency

For any dependency that you need in your app, you must register a provider with the application's injector, so that the injector can use the provider to create new instances. For a service, the provider is typically the service class itself.

A dependency doesn't have to be a service —it could be a function, for example, or a value.

How it works?

When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of HeroListComponent needs HeroService.

constructor(private service: HeroService) { }

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider and adds it to the injector before returning the service to Angular.

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.


Backlinks