Angular 2 Dependency injection

Angular 2 Dependency injection

Angular 2 Dependency injection is a way to create objects that objects are dependent on other objects. The purpose of Angular 2 Dependency injection is to simplify dependency management.

Angular has @Injectable()decorator that lets you manage dependency.

Steps to use dependency management

  1. Create an Injectable service class.
  2. Register Injectable service in providers section inside any main @Module, service is just a normal class until we register this component class with an Angular dependency injector.
  3. We can tell Angular to inject a dependency in the component’s constructor by specifying a constructor parameter with the dependency type.

Step 1 – Create @Injectable service

import { Injectable } from '@angular/core';
import { Logger} from './logger-service';

export class LoggerService{

Step 2- Register above service class into any Module

Here we will register Logger service into main module.

import { NgModule } from ‘@angular/core’;
import { LoggerService}  from ‘./logger.service’;

  declarations: [
       imports: [],
       providers: [],
       bootstrap: [ LoggerService ]

export class AppModule {


Step 3 – Inject service and use

export class LoginComponent { 
   name: string = ""; 
   constructor(private _loggerService: LoggerService) { 

Now we can use Logger Service because Angular injected all dependent object internally.

Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: Sales: +91 8085506229