Understanding Dependency Injections in Angular

Athif Shaffy
2 min readJan 23, 2019

What is Dependency Injections

A dictionary definition of Dependency Injection would be something like:

A coding pattern in which a class receives the instances of objects it needs(called dependencies) from an external source rather that creating them itself.

I have been using Angular’s dependency injections for sometime now without really understanding what actually happens behind the scene. This post attempts to show how Angular’s Dependency Injections work behind the scene.

Ways of using a service for data sharing.

  1. Create a new instance of service class every time it is used

For example if you create a network service, you use it for components and pages by creating a new instance of the service class.

(Source: Deborah Kurata, 2018)

This is simple but instance is local to the component or page using it therefore it can’t be shared, in addition for it being difficult to mock the service for testing.

2. Use Angular Dependency Injection.

How does Angular Dependency Injection work?

When an Injector annotation is specified for a service class, the specified instance is stored in Angular’s inbuilt Injector. Angular’s Injector is a container which creates and manages single instance(Singleton) of each registered service.

If you have used Angular’s Dependency Injections for service classes it would look something like the following.

import { Injectable } from ‘@angular/core’;@Injectable()
export class myService {}

Behind the scene, Angular’s Injector container has something like the following, where the Injector has a service called myService(abbv as svc) in the Injector Container and whenever the service is needed in a component it is injected into the constructor when the component is instantiated.

(Source: Deborah Kurata, 2018)

Further References

--

--

Athif Shaffy

Senior Software Engineer | Freelance developer | Interested in History and Philosophy