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.
- Create the service
- Register the service.
- Inject the service and use
To build the below screen we need one component:
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:
- import {
- Injectable
- } from '@angular/core';
- @Injectable()
- export class StudentListService {
-
- getAllStudents() {
- return [{
- Id: 1,
- Name: "Mahesh",
- Address: "Thane",
- Gender: "Male"
- }, {
- Id: 2,
- Name: "Nishikant",
- Address: "Chembur",
- Gender: "Male"
- }, {
- Id: 3,
- Name: "Sameer",
- Address: "Mulund",
- Gender: "Male"
- }, {
- Id: 4,
- Name: "Nitin(Johny)",
- Address: "Mulund",
- Gender: "Male"
- }, {
- Id: 4,
- Name: "Siri",
- Address: "Worli",
- Gender: "Female"
- }];
- }
- }
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
- import {
- Component,
- OnInit
- } from '@angular/core'
- import {
- StudentListService
- } from './student-list.service';
- @Component({
- selector: 'my-app',
- templateUrl: './app/app.component.html',
- providers: [StudentListService]
- })
- export class AppComponent implements OnInit {
- public students: any = [];
-
-
- constructor(private _studentListService: StudentListService) {}
-
- ngOnInit() {
-
- this.students = this._studentListService.getAllStudents();
- }
- }
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:
- <div class="container">
- <table class="table table-sm">
- <thead>
- <tr>
- <th scope="col">Id</th>
- <th scope="col">Name</th>
- <th scope="col">Address</th>
- <th scope="col">Gender</th>
- </tr>
- </thead>
- <tbody>
- <!--using *ngFor directive to iterate over student list-->
- <tr *ngFor="let student of students">
- <th scope="row">{{student.Id}}</th>
- <td>{{student.Name }}</td>
- <td>{{student.Address}}</td>
- <td>{{student.Gender}}</td>
- </tr>
- </tbody>
- </table>
- </div>
In the above code I am rendering the students using the *ngFor structural directive.
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