Understanding Dependency Injections in Angular

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.

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.

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.

Further References

Senior Software Engineer at 99x | Freelance developer | Interested in History and Philosophy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store