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 {...}
 
class Car { 
  engine; 
  transmission;
 
  constructor() { 
    this.engine = new Engine(); 
    this.transmission = new Transmission(); 
  } 
} 

In the preceding example, we create the dependencies of the Car class inside its constructor. Although it looks simple, it is far from being flexible. Each time we create an instance of the Car class, in its constructor, instances of the same Engine and Transmission classes will be created. This may be problematic because of the following reasons:

  • The Car class gets less testable because we can't test it independently of its engine and transmission dependencies.
  • We couple the Car class with the logic used for the instantiation of its dependencies.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset