How To Use Services In Angular

Introduction

In this article, we are going to learn how the services in Angular are being created and used. We will also learn why we create services and how we achieve dependency injection in Angular.

Prerequisites

  • HTML, CSS, and JS
  • Basics of TypeScript.

Note
See my previous article “Services in Angular” and create the application using Services.

So, we have the application that is utilizing the service and we know what the dependency injection is and how we avoid the repetition of code.

Service In Angular 

So. in our application, there is a student service that provides the details and marks of the students and we don’t have to worry about the data in both the components. We are simply getting the data and rendering it to the Template View of both the components.

When we generate a service through Angular CLI, it will generate the basic template of the service. We have modified the contents and completed the first step in generating the service.

  1. import { Injectable } from '@angular/core';  
  2.   
  3. @Injectable({  
  4.   providedIn: 'root'  
  5. })  
  6. export class StudentService {  
  7.   students = [  
  8.     {"id" : 1001, "name" : "Irshad""marks" : 90},  
  9.     {"id" : 1002, "name" : "Imran""marks" : 80},  
  10.     {"id" : 1003, "name" : "Rahul""marks" : 70},  
  11.     {"id" : 1004, "name" : "Ajay""marks" : 85},  
  12.     {"id" : 1005, "name" : "Sunny""marks" : 60}  
  13.     ];  
  14.   constructor() { }  
  15.   getStudents(){  
  16.     return this.students;  
  17.   }  
  18. }  

Now, the second step is to register the service. If we don’t register the service, then it will be considered as a regular class of Angular. There is a different way of registering the service in Angular. It will maintain the hierarchy of dependency injection.

Service In Angular 

If we register the service to the AppModule, i.e, in the top level, then it will be available to all the components. AppComponent, StudentDetails, StudetntMarks, and so on. All will be able to use this service by injecting it through dependency injection.

Service In Angular 

In the above diagram, we are registering the service to the StudentDetails component, then the child components and itself StudentDetails Component will be able to use this service and other Components like StudentMarks component will not be able to use this service.

In simple words, the component which is having the service registered will be able to use the service and its child component will be able to use the service.

So, we have to take care of the creation and registration of the service while developing the application. It is always good to register the service to the AppModule so that it will not create a problem in injecting it to any component and to register it to the module. It will use the provider metadata.

In the app.module.ts, we have registered it as below.

First, we imported the service. 

  1. import { StudentService } from './student.service';  

Then, we registered it.

providers: [StudentService]

The two above statements will already be done by Angular CLI. So, now we are done with the registration of the service. Now, we are going to mention the service to the component that needs to utilize the service.

In the student-details.component.ts, we are going to utilize this service by using the syntax of dependency injection to the constructor. Open student-details.component.ts and see the below contents.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { StudentService } from '../student.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-student-details',  
  6.   templateUrl: './student-details.component.html',  
  7.   styleUrls: ['./student-details.component.css']  
  8. })  
  9. export class StudentDetailsComponent implements OnInit {  
  10.   
  11.   public students = [];  
  12.   constructor(private studentService : StudentService) {   
  13.   }  
  14.   
  15.   ngOnInit() {  
  16.     this.students = this.studentService.getStudents();  
  17.   }  
  18. }  

We have injected the service called dependency injection also, as below in the constructor.

  1. constructor(private studentService : StudentService) {  

Also, don’t forget to import the service.

  1. import { StudentService } from '../student.service'

The ‘studentService’ object will have the reference to the StudentService. It is better to utilize the fetching of data inside ngOnInit() method of the component because ngOnInit() method is called once the component has been initialized.

Use of Injectable decorator in the component

Open student.service.ts.

  1. import { Injectable } from '@angular/core';  
  2.   
  3. @Injectable({  
  4.   providedIn: 'root'  
  5. })  
  6. export class StudentService {  
  7.   students = [  
  8.     {"id" : 1001, "name" : "Irshad""marks" : 90},  
  9.     {"id" : 1002, "name" : "Imran""marks" : 80},  
  10.     {"id" : 1003, "name" : "Rahul""marks" : 70},  
  11.     {"id" : 1004, "name" : "Ajay""marks" : 85},  
  12.     {"id" : 1005, "name" : "Sunny""marks" : 60}  
  13.     ];  
  14.   constructor() { }  
  15.   getStudents(){  
  16.     return this.students;  
  17.   }  
  18. }  

@Injectable defines that this service might also inject some dependencies. So, if you want the service to be injectable to another service, then you must define the Injectable decorator. Don’t include this decorator if you are sure this will not inject any other service. It is recommended to add the @Injectable decorator as soon as we create the service class. Angular CLI already adds this decorator when creating the service.

The component class has a @Component decorator that lets us know if it may have dependency injection systems. But for service, there is no @Component decorator. If we remove the @Injectable decorator, then it will become a plane class and there is nothing to do with the service. So, to make the service, the @Injectable decorator is required.