Welcome to the free & complete Angular Tutorial.

This post is all about Introduction to Services in Angular and Dependency Injection (DI).

Services play important role in doing the utility activities for components like Logging, retrieving data from remote server etc.,

To know about Angular Architecture, below posts will help you.

Angular Architecture Overview

Angular Architecture Explained

Let’s get started.

What is Services?

A service in Angular is any data, function, feature that an Application needs. It is written as a typical class with structured and well defined purpose.

All we need Service to do is do something specific like Log application flow in Console while application running in development mode, listen to keyboard key hits, post data to rest api etc.,

Why services?

You may think you can achieve above said things just within Component without Service class, then why we need Services.

Here is the answer to your question !

Say suppose you need to have the same piece of Utility code (assume logging) across components, that will result in redundant code exist in multiple places of application. Using Service class save us in this situation, as this will be injected across components that want to use the functionality of service class that increases code modularity and reusability.

Component is for user experience, display data on UI; Service is to fetch data and pass it to Component, or do something that component wants to.

How to create Service?

Use Angular CLI to create Service class, execute below command in CMD prompt:

ng generate service <Service name>

Quick example

Let’s create simple logger service under Angular project using CLI:

ng generate service logger

You will see Service class created with @Injectable decorator and registered with Root level provider:

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

@Injectable({
  providedIn: 'root'
})
export class LoggerService {

  constructor() { }

}

We will add few methods to it:

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

@Injectable({
  providedIn: 'root'
})
export class LoggerService {

  constructor() { }

  logInfo(msg: string){
    console.log('Logging service: ' + msg);
  }

  logError(err: string){
    console.error('Logging service: ' + err);
  }
}

Dependency Injection

Dependency Injection (DI) is a mechanism in Angular Framework that provides components with Services (Basically utility functions).

Let’s use one of the Service method in Component by injecting Service object in Component’s constructor:

import { Component } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Hello World App';
  constructor(logSvc: LoggerService){
    logSvc.logInfo('App component has been executed..');
  }
}

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn’t yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.