Angular - Understanding Service

In this article we are going to talk about Service in Angular.

As we know, Component is the basic building block of Angular applications, and component is responsible for handling the UI-related logic only. But in my previous article, I was creating the student array in constructor of component which works properly, but as per coding standards, we have violated the SRP; i.e., Single Responsibility principle. Then to overcome this problem service will come into the picture to help us.

In Angular, service is nothing but a simple typescript class created for a specific purpose. The purpose of service might be one one of the following:

  • To write the business logic.
  • To provide shared data to the components.
  • To handle the external interactions, like to get the data from API.

So in this article we will learn about how to create the service to provide the shared data and how to consume service, please note that I have used bootstrap classes to add some basic style.

To create and consume service in Angular we need to follow the below steps.

  1. Create the service
  2. Register the service.
  3. Inject the service and use

To build the below screen we need one component:

Service in Angular

AppComponent 

This component is responsible for displaying the student list but the data will come from the service as we are not hard coding student array in constructor.

Step 1 - Create the service

Create .ts file and name it student-list.service.ts and paste the below code:

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. @Injectable()  
  5. export class StudentListService {  
  6.     // This method will return us the list of students  
  7.     getAllStudents() {  
  8.         return [{  
  9.             Id: 1,  
  10.             Name: "Mahesh",  
  11.             Address: "Thane",  
  12.             Gender: "Male"  
  13.         }, {  
  14.             Id: 2,  
  15.             Name: "Nishikant",  
  16.             Address: "Chembur",  
  17.             Gender: "Male"  
  18.         }, {  
  19.             Id: 3,  
  20.             Name: "Sameer",  
  21.             Address: "Mulund",  
  22.             Gender: "Male"  
  23.         }, {  
  24.             Id: 4,  
  25.             Name: "Nitin(Johny)",  
  26.             Address: "Mulund",  
  27.             Gender: "Male"  
  28.         }, {  
  29.             Id: 4,  
  30.             Name: "Siri",  
  31.             Address: "Worli",  
  32.             Gender: "Female"  
  33.         }];  
  34.     }  

In the above code I have just created Typescript class StudentListService and decorated that class with the @Injectable() decorator. This is not mandatory but it is recommended to use this decorator. We will talk about this in a separate article if this doesn’t make sense to you.
I have added one method, getAllStudents, in service which is simply returning the list of students.

Step 2 - Register the service

We can register the service at two levels by using [Provider] metadata attribute.

  • Module Level
    If we register the service at module level then that service will be available to all the components inside that module

  • Component Level
    If we register service at component level then that service will be available to that component and all the child components of respective components.

In this example I am registering the service at component level.

Open the app.component.ts file and paste the below code

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core'  
  5. import {  
  6.     StudentListService  
  7. } from './student-list.service';  
  8. @Component({  
  9.     selector: 'my-app',  
  10.     templateUrl: './app/app.component.html',  
  11.     providers: [StudentListService] // Here we have registered the service at the component level.  
  12. })  
  13. export class AppComponent implements OnInit {  
  14.     public students: any = []; // this variable holds the list of students that we will get from the service  
  15.     //In constuctor we are injecting the service using typescripts shorthand syntax  
  16.     //we will talk about dependancy injection in separate article  
  17.     constructor(private _studentListService: StudentListService) {}  
  18.     //This is lifecycle hook method of angular which fires after the constructor  
  19.     ngOnInit() {  
  20.         //here i am calling the services and assingning the returned student list to the students variable  
  21.         this.students = this._studentListService.getAllStudents();  
  22.     }  
  23. }  

In the above code I have registered service at component level using provider metadata tag

And in the constructor of component I am injecting that service, again if you are not clear about dependency injection we will talk about that in a separate article.

And in the ngOnInit method of Angular lifecycle hook I am calling the service to get the student list.

Step 3

Open the app.component.html and paste the below code:

  1. <div class="container">  
  2.     <table class="table table-sm">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th scope="col">Id</th>  
  6.                 <th scope="col">Name</th>  
  7.                 <th scope="col">Address</th>  
  8.                 <th scope="col">Gender</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <!--using *ngFor directive to iterate over student list-->  
  13.             <tr *ngFor="let student of students">  
  14.                 <th scope="row">{{student.Id}}</th>  
  15.                 <td>{{student.Name }}</td>  
  16.                 <td>{{student.Address}}</td>  
  17.                 <td>{{student.Gender}}</td>  
  18.             </tr>  
  19.         </tbody>  
  20.     </table>  
  21. </div>  

In the above code I am rendering the students using the *ngFor structural directive.

Html output screenshot

Html output screenshot

 

In the above image we are getting the student list from the service.

In our next article, we will learn about Angular dependency injection and how to use http services to get the data from the API.

Hope this will help you.

You can download the complete code from my github repository using below link.

https://github.com/mahesh353/service


Similar Articles