Chapter 5. Dependency Injection in Angular

In this chapter, we'll explain how to take advantage of the dependency injection (DI) mechanism of the framework, with all its various features.

We will explore the following topics:

  • Configuring and creating injectors.
  • Instantiating objects using injectors.
  • Injecting dependencies into directives and components-this way, we will be able to reuse the business logic defined within the services and wire it up with the UI logic.
  • Annotating ES5 code in order to get the exact same result we get when we use the TypeScript syntax.

Why do I need DI?

Let's suppose that we have a Car class that depends on Engine and Transmission classes. How can we implement this system? Let's take a look:

class Engine {...} class Transmission ...

Get Getting Started with Angular - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.