Day 03: Services and Interceptors

Day 03: Services and Interceptors

In this part of Angular tutorial, we will learn Services and Interceptors with code examples. Before we move into that, we need to have a quick overview of Dependency Injection.

What is Dependency Injection in Angular?

Dependency Injection (DI) is a mechanism used in Angular applications to divide some parts of the code and create a new class or module to use it throughout the application, usually across more than one component.

However, this can be anything but to make HTTP requests in Angular, services are created which are a best example of a Dependency Injection. To identify a class as an injector, the @Injectable decorator is added to it. Then, we need to add this to our module & component as a provider where we intend to use this service. Do checkout the example below:


// employee.service.ts file
@Injectable({
  providedIn: 'root'
})
class EmployeeService {}

// employees.module.ts file
@NgModule({
  declarations: [EmployeesComponent]
  providers: [EmployeeService]
})
class EmployeesModule {}

// employees.component.ts file
@Component({
  selector: 'app-employees',
  template: './employees.html',
  providers: [EmployeeService]
})
class EmployeesComponent {
  constructor(
    private empService: EmployeeService
  ) {}
}

This is a basic example of the skeleton to be developed for creating a new service.ts file in Angular. Now, we will explore more about creating a full-fledge service.ts file for making HTTP get/post requests with a live business example.

How to create a Service in Angular?

To generate a new service.ts file in Angular, run the below command in your CLI:

ng generate service employees/employee

It will generate a file as shown in the screenshot below:

Let's go through some code samples to understand how a service can be created in Angular and how a model can be created to move part of the application for reuse in service file.

import { Injectable } from '@angular/core';
import { SAMPLEDATA } from './sample-data';

@Injectable({
  // signifies that the service should be created by the root application injector
  providedIn: 'root',
})
export class EmployeeService {
  getEmployees() {
      return SAMPLEDATA.EMPLOYEES;
  }
}

Share this blog on:

Deepak Jain, Full-stack Developer, Blogger and Tech Consultant

About Author

Deepak Jain is an experienced professional full-stack developer, UI/UX designer, ex-startup entrepreneur, passionately writes blog on technology, startups, business ideas. He also shares his own life experiences and creates awesome inspiring stories from the lives of people. Check out full profile