Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

What Is Dependency Injection in Angular And How to create one?

Hi friends! Welcome to my Angular course. In the previous lesson, we explored services—what they are and how to create one.

We also learned about creating an instance of a service manually, but I mentioned that this is not the correct way in Angular. Instead,

Angular has a powerful feature called Dependency Injection (DI), which is the preferred approach. So, let’s dive deeper into dependency injection and understand why it’s so important in Angular applications.

What is Dependency Injection?

Dependency Injection is a design pattern where objects are provided with their dependencies rather than creating them manually.

In Angular, this means that if a class needs a certain dependency—such as a service—Angular will inject that dependency into the class automatically.

For example, if your component needs a logging service, you don’t have to create an instance of that service manually. Instead, Angular will handle that for you.

Understanding Components and Classes

Although we often think of Angular components as a special kind of entity, remember that they are just classes. If a component needs to log something to the console, it will require a logging service.

To make the logging service available to the component, dependency injection is used to provide an instance of the service to the component class.

Why Should You Use Dependency Injection?

Manually instantiating services like this:

let loggingService = new LoggingService();

isn’t ideal in Angular because:

  1. Tight Coupling: It tightly couples your component with the service, making it harder to swap out the service later if needed.
  2. Testability Issues: It makes unit testing more difficult because you can’t easily mock services during testing.
  3. Scalability: As your app grows, manually creating instances everywhere becomes cumbersome.

Angular’s dependency injection solves these problems by automating the process of providing the service instances to your components.

How Does Angular Inject Dependencies?

Angular takes care of creating and providing instances of services, components, and other objects.

For example, when you use an *ngFor directive in a template, you aren’t explicitly creating its instance—Angular does that behind the scenes.

Let’s go through how dependency injection works in Angular.

Step 1: Tell Angular You Need a Service

You need to let Angular know that your component requires a service. This is done in the constructor of your class:

constructor(private loggingService: LoggingService) {}

Here, the LoggingService is injected into the component through the constructor. By making it private, the component now has access to the service via this.loggingService.

Step 2: Register the Service with Angular

Angular doesn’t automatically know where your service is. You need to register the service using the providers array in your component’s decorator:

@Component({
  selector: 'app-user',
  providers: [LoggingService]
})

By adding LoggingService to the providers array, you are telling Angular where to find the service so that it can inject it into your component.

Example: Injecting a Logging Service

Here’s how you would inject a logging service into a user component and use it:

export class UserComponent {
  constructor(private loggingService: LoggingService) {}

  addUser(username: string) {
    this.loggingService.logToConsole(`User ${username} added`);
  }
}

In this example, Angular takes care of creating an instance of LoggingService and injecting it into the UserComponent.

You can then use the logToConsole method whenever needed without worrying about the service’s instantiation.

The Advantage of Dependency Injection

By using DI, you are allowing Angular’s ecosystem to handle object creation and management. This improves:

  • Code Reusability: Services can easily be reused across different parts of the application.
  • Loose Coupling: Your components become loosely coupled with services, making it easier to change or replace services without modifying much code.
  • Testing: It becomes much easier to mock services during testing, enabling better test coverage.

Wrapping Up

Dependency injection is a core concept in Angular, allowing you to write cleaner, more maintainable, and scalable applications.

You no longer need to worry about manually managing instances of services.

Angular will take care of it, thanks to its DI framework.

In upcoming lessons, we’ll dive deeper into more advanced topics and the benefits of DI. But for now, you’ve learned how to effectively inject services into components using Angular’s dependency injection system.

If you have any questions, feel free to comment below! Don’t forget to subscribe for more Angular tips and tutorials.

Happy coding! 😊