Dependency Injection in Angular

Dependency injection(DI) is one of the core concepts of Angular. It is used to provide the dependencies to the class by injecting the services or any other things that are needed by the component.

In angular, the service(s) can be injected to the component's in its constructor. So when angular creates a new instance for a component, it looks for the constructor of the component and checks for any parameter(s).

If the service contains any parameter specifying any service type, then it checks if the injector(Holds the instance of the services) has any instance of the service.

If the service instance is present in the injector, the injector returns the instance of the service so that the constructor of the component can be called.

If the service instance is not present in the injector, then the injector creates an instance of the service if the service is declared in the providers array of the module or the component.

Once all the dependent services are resolved and returned, then the constructor of the component can be called.

Let's see how to create a service and inject it to a component. Assume we have a UserService with the following code.

import { Injectable } from '@angular/core';
    
@Injectable({
    providedIn: 'root'
})
export class UserService {
    
private userName:string;
constructor() { }
    
setUser(userName:string) {
    this.userName = userName;
}
    
getUser(){
    return this.userName;
}
}

In order to use the function in the service in app.component.ts, we have to inject the service to the constructor of the component.

Modify the code of app.component.ts file like below.

import { Component } from "@angular/core";
import { UserService } from "./services/user.service";
    
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
    constructor(private userService: UserService) {
        this.userService.setUser("Readers Buddy!");
    }
}

Here we have imported the UserService and injected the service to the constructor and then call the setUser() function of the UserService using the object name.

With the help of Dependency Injection we no need to worry about creating instances for the services and using them. Angular looks after it by providing the resources needed by the component by means of Dependency Injection.


Most Read