DEV Community

Cover image for Understanding Angular Dependency Injection by building app
josematoswork
josematoswork

Posted on • Originally published at angulardive.com

Understanding Angular Dependency Injection by building app

Understanding Angular Dependency Injection by building an App

As an Angular developer, understanding the concept of Dependency Injection is crucial for building scalable and maintainable applications. Dependency Injection is a design pattern in software engineering that allows dependencies to be passed to an object rather than being instantiated within the object. This helps to reduce tight coupling within the code and allows for better scalability and maintainability. In this article, we’ll dive into the world of Angular Dependency Injection by building an app.

What is Dependency Injection in Angular?

In Angular, Dependencies are objects or services that a component or service relies on to function properly. To use these dependencies, we need to create instances of them in the code. This can lead to problems like tight coupling, hardcoding, and code duplication.

Angular’s Dependency Injection allows us to avoid these problems by creating instances of dependencies at runtime rather than at compile time. This means that Angular will create instances of required services and pass them to components as-needed.

So, instead of defining service instances in each component or service, we can use Angular’s Dependency Injection to define it once and then use it globally. This promotes better and cleaner code organization.

How does it work?

To understand how Angular Dependency Injection works, we need to understand the basic concepts of Angular services, providers, and injections.

Angular Services

Angular Services are objects or functions that are used to share data or functionality between components. They can be injected into a component and used to perform certain tasks, such as fetching data from an API.

A Service in Angular is a singleton instance which means it is created once and used throughout the entire application.

Here’s an example of a simple Service:


import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  users = ['John', 'Jane', 'Sam'];

  constructor() { }

  getUsers() {
    return this.users;
  }

  addUser(user: string) {
    this.users.push(user);
  }
}

In this example, we defined a Service named ‘UserService’ which has a list of users and two methods, getUsers() and addUser(). To make this Service available to the application or component, we need to include it in Angular’s Dependency Injection.

Providers

In Angular, Providers are objects that are used to provide a certain type of service to the application. A Provider can be defined in the component, or we can register it in the module.

Angular uses Providers to associate a Service with the module or component that is requesting it. A Provider can be a Service, an object, or a factory function that returns a value.

Here’s an example of how to register a Service as a Provider:


import { NgModule } from '@angular/core';
import { UserService } from './user.service';

@NgModule({
  imports: [],
  exports: [],
  declarations: [],
  providers: [UserService]
})
export class AppModule { }

In this example, we register the UserService as a Provider in the AppModule. When we do this, Angular will create a single instance of the UserService and make it available throughout the entire application.

Injectors

An angular injector is an object responsible for creating and injecting dependencies. We need to provide injectors with a set of instructions to follow regarding how to create and inject dependencies. These instructions are in the form of Providers.

In the App Module, we may define a provider for a service, and Angular’s Injector will take care of everything else. It will create an instance of the Service and then inject it into the components that require it.

Dependency Injection in Components

To use a Service in an Angular Component, we need to inject it using the constructor. Here’s an example:


import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent {
  users = [];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.users = this.userService.getUsers();
  }

}

In this example, we inject the UserService in the constructor of the UsersComponent. We then store the data returned by the service in the users variable.

In Conclusion

In this article, we’ve covered some of the basics of Angular Dependency Injection. We’ve looked at what Dependency Injection is, how it works in Angular, and how to use it in Components.

Angular’s Dependency Injection reduces code duplication, promotes maintainability, and allows for better scaling of applications. In addition, it makes it easier to maintain and test our applications.

As an Angular developer, understanding how Dependency Injection works is crucial for developing scalable and maintainable applications. I hope this article has provided you with the foundational knowledge you need to start implementing Angular Dependency Injection in your applications.

Top comments (0)