Services In Angular

In this article, we are going to utilize the Angular Services. Service is nothing but the class having certain operations for a specific purpose. We use Services in Angular to share data among the components.

Introduction

In this article, we are going to utilize Angular Services. A Service is  a class having certain operations for a specific purpose. We use services in Angular to share the data among components. In an application, the service is responsible for providing the data to the component. So, the sharing of data is also one of the responsibilities of the service. Another facility that the service provides is application logic. We create the service that has a certain logic and utilizes that in the component so as to make the component directly using the logic/operations without binding that logic to the component individually. We create a service for a certain request that interacts externally to get the data from somewhere and give that to the View. We can perform so many operations by using Services in Angular.

Prerequisites

  • HTML, CSS, and JS
  • Basic coding knowledge of TypeScript
  • Components

Let us create a sample TestApp. For this, you should have the below for development environment installed.

  1. Node
  2. Npm (comes when you install node)
  3. Angular CLI
  4. Text Editor.

For creating a new application, run the below command on your preferred location.

> ng new TestApp

Once your command is completed, you will have TestApp folder created inside your sample folder.

Note
See my previous article “Getting started with Angular CLI” if you want to learn the installation and introduction from the basics and want to get started with the execution of sample application.

Let us start with a simple application having details of students in two different comonents. Create two components -

  • >ng g c student-details
  • >ng g c student-marks

The following files will be added.

Services In Angular 

Open student-details.component.ts and add the below code.

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-student-details',  
  5.   templateUrl: './student-details.component.html',  
  6.   styleUrls: ['./student-details.component.css']  
  7. })  
  8. export class StudentDetailsComponent implements OnInit {  
  9.   
  10.   public students = [  
  11.   {"id" : 1001, "name" : "Irshad""marks" : 90},  
  12.   {"id" : 1002, "name" : "Imran""marks" : 80},  
  13.   {"id" : 1003, "name" : "Rahul""marks" : 70},  
  14.   {"id" : 1004, "name" : "Ajay""marks" : 85},  
  15.   {"id" : 1005, "name" : "Sunny""marks" : 60}  
  16.   ];  
  17.   constructor() { }  
  18.   ngOnInit() {  
  19.   }  
  20. }  

Open student-details.component.html and add the below lines of code.

  1. <h2>Student Details:</h2>  
  2. <div *ngFor="let stud of students">  
  3.   Id : {{stud.id}}, Name : {{stud.name}}  
  4. </div>  

Open student-marks.component.ts and add the below lines.

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-student-marks',  
  5.   templateUrl: './student-marks.component.html',  
  6.   styleUrls: ['./student-marks.component.css']  
  7. })  
  8. export class StudentMarksComponent implements OnInit {  
  9.   
  10.   public students = [  
  11.     {"id" : 1001, "name" : "Irshad""marks" : 90},  
  12.     {"id" : 1002, "name" : "Imran""marks" : 80},  
  13.     {"id" : 1003, "name" : "Rahul""marks" : 70},  
  14.     {"id" : 1004, "name" : "Ajay""marks" : 85},  
  15.     {"id" : 1005, "name" : "Sunny""marks" : 60}  
  16.     ];  
  17.   constructor() { }  
  18.   ngOnInit() {  
  19.   }  
  20. }  

Open student-marks.component.html and add this code.

  1. <h2>Marks Details:</h2>  
  2. <div *ngFor="let stud of students">  
  3.   Id : {{stud.id}}, Marks : {{stud.marks}}  
  4. </div>  

Open app.component.html and add the following code.

  1. <!--The content below is only a placeholder and can be replaced.-->  
  2. <div style="text-align:center">  
  3.   <h1>  
  4.     Welcome to {{ title }}!  
  5.   </h1>  
  6.   <app-student-details></app-student-details>  
  7.   <br>  
  8.   <app-student-marks></app-student-marks>  
  9. </div>  

Run the application.

Services In Angular 

The above application is working but it is not a good programming practice. You can see that we have added the same set of data to both the files - student-details.component.ts and in student-marks.component.ts.

  1. public students = [  
  2.     {"id" : 1001, "name" : "Irshad""marks" : 90},  
  3.     {"id" : 1002, "name" : "Imran""marks" : 80},  
  4.     {"id" : 1003, "name" : "Rahul""marks" : 70},  
  5.     {"id" : 1004, "name" : "Ajay""marks" : 85},  
  6.     {"id" : 1005, "name" : "Sunny""marks" : 60}  
  7.     ];  

This same data is being used in both the components, which means the component is not only responsible for displaying or working with the data, it is also taking the responsibility of generating the data, which actually should not be its responsibility. These components should only be responsible to use the given data. This is breaking the single responsibility rule of the programming.

Here comes Angular Services into the picture. We should have a service that will be injected into these two components and should solely be responsible to deliver the data to these components. These components should only perform one responsibility: dealing with how to use the data given by the service.

So, when we inject the service, the component will only use the data given by the Service instead of knowing how the data is coming from that service. This makes the service responsible for generating the data and components are responsible to make it display.

Let us start creating a service and use that in your application.

>ng generate service student

Services In Angular 

Open student.service.ts and add the below code.

  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. }  

Open app.module.ts and add these services in provider.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule, Pipe } from '@angular/core';  
  3. import {FormsModule} from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { TestComponent } from './test/test.component';  
  6. import { StudentDetailsComponent } from './student-details/student-details.component';  
  7. import { StudentMarksComponent } from './student-marks/student-marks.component';   
  8.   
  9. @Pipe({  
  10.   name: "namePipe"  
  11. })  
  12.   
  13. class NamePipe{  
  14.   transform(value : string, defaultValue : string) : string{  
  15.     if(value != ""){  
  16.       return value;  
  17.     } else {  
  18.       return defaultValue;  
  19.     }  
  20.   }  
  21. }  
  22.   
  23. @NgModule({  
  24.   declarations: [  
  25.     AppComponent,  
  26.     TestComponent,  
  27.     NamePipe,  
  28.     StudentDetailsComponent,  
  29.     StudentMarksComponent  
  30.   ],  
  31.   imports: [  
  32.     BrowserModule,  
  33.     FormsModule  
  34.   ],  
  35.   providers: [],  
  36.   bootstrap: [AppComponent]  
  37. })  
  38. export class AppModule { }  

Open student-details.component.ts and add the below code.

  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.     this.students = studentService.getStudents();  
  14.   }  
  15.   ngOnInit() {  
  16.   }  
  17. }  

Open student-marks.component.ts and add this code.

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

Run the application.

Services In Angular 

You have achieved the same thing that we got in our previous example, however, this time, the data is coming from a service and our component is only performing single functionality, i.e., to render the data.