Member-only story

Dependency Injection in Angular

That Jeff Guy
4 min readFeb 17, 2018

So I’m reading up on Angular these days, and one of the cool things about it is Dependency Injection. As a Spring developer, I’m quite familiar with the inversion of control and how it can make your applications much more flexible and easier to test. If you aren’t familiar with it, I suggest you look it up on Wikipedia. The basic idea, however, is that you define a type like a car, and inject into it the various dependencies rather than building them inside. The Angular analogy in TypeScript looks something like this:

By annotating the class with the @Injectable annotation, you are basically indicating that Angular should resolve dependencies from providers when this type is constructed. The example car above has several dependencies like the engine, wheels, etc. In this way, the logic within the Car type doesn’t have to worry about how these things are constructed or really what is inside of them. From the perspective of the Car, they are black boxes that expose an API.

The real power of dependency injection, however, is that because the items being injected are black boxes, the contents inside the…

--

--

That Jeff Guy
That Jeff Guy

Written by That Jeff Guy

I'm a technology enthusiast, always searching for better ways of doing things. Lately that has been all things React/Angular. I also write a lot on Medium. :)

No responses yet