...

/

Understanding Dependency Injection

Understanding Dependency Injection

In this lesson, we'll take the time to learn about dependency injection in Angular.

Dependency injection is one of those things that can be difficult to wrap your head around. It’s a feature in Angular that makes our lives so much easier. Let’s look at why dependency injection is great and how it works in Angular.

Drawbacks without dependency injection

We’ll step away from our project for a moment. First, we’re going to look at some of the problems we’ll encounter without dependency injection.

Let’s look at an example.

Press + to interact
class engine {
}
class car {
engine;
constructor() {
this.engine = new engine();
}
}

In the example above, we have two classes: engine and car. The car class creates a new instance of the engine object. It’s assigned to a property called engine. This makes the engine class a dependency of the car class. It relies on the engine class to work.

This example works, but it isn’t scalable. Let’s see what would happen if we added a property to the engine class.

Press + to interact
class engine {
fuel;
constructor(fuel){
this.fuel = fuel;
}
}
class car {
engine;
constructor() {
this.engine = new engine('gas');
}
}

This time around, we’re creating a ...