Harnessing Angular’s Dependency Injection

Chris Camac
2 min readFeb 12, 2020

The Angular framework does a lot of heavy lifting for you when creating a dynamic web application. One of the key functions is dependency injection, which is how we can share logic between classes. What if we wanted to use this powerful feature in a standalone class? Can that even be accomplished?

Yes. It can, and it’s pretty easy to setup. Let’s go over an example and show you exactly how to do it.

The Example

Let’s say that you are working on an application that features posts with timestamps. In this application, you have a class the represents the post named as Post. Since you want to centralize the logic for formatting the display of the post’s timestamp, you plan to create a function for this named as getFormattedTimestamp. Below is a version of this class and function that would use the Angular DatePipe.

In the class above, the DatePipe is being passed in using the constructor. This certainly works, but makes this class and everywhere it is used a lot less maintainable. What if you choose to use some other injected item later? Or decided to use some service other than DatePipe? That could get messy and costly very quickly.

A Better Way

If you could get the injected resource directly from within the static class, then you could eliminate the constructor parameter and make this class more self contained. Through the use of a global injector, this can be achieved.

A global injector is when you take the injector object itself and store it in a global variable, allowing you to use dependency injection from any file used in your Angular application, including static files like the Post class.

Below are files showing how to setup the global injector.

Now that you have setup the globalInjector object, you can refactor the Page class to use it like below.

Conclusion

Using these techniques you can harness the power of dependency injection throughout your entire angular application, even when dealing with static files. This leads to a much more maintainable and extensible application structure.

--

--

Chris Camac

Full stack dev, open source enthusiast, fledgling bass player, old guy at your EDM concert, teacher, speaker, disgustingly lucky