Services in Angular

Components should not be used to fetch or save data directly. So the question arises, then how should we store and fetch data. The solution to this problem can be solved by using services.
Services in angular are used to share information among components or classes. That information can be of business logic, models, data, properties, and functions.

Why use services in angular?

Components are responsible for binding data to the view. An angular application can contain many components and it is unnecessary to make a call to the server every time we want specific data. So to solve this problem we can create a service that makes a call to the server and then we can use that service in components to access that data. Services can contain different functions and each function can make different calls to the server to fetch a different kind of data. We can use these functions from services into components to access different data. In this way, components don’t have to fetch data.

How to create a service?

You can create a service using the following command:

ng generate service userdata

where userdata is the name of the service.

Example of using Service:

Step 1: Creating a service

Create a service named userdata using the following command:

ng generate service userdata

By using this command angular-cli will create necessary files for service and will also provide that service in AppModule. Services need to provided in AppModules so that all components from an application can access that service.
From the following image, you can see files created related to userData service.

userdata.service.spec.ts file is used for testing purpose.

Step 2: Using service to fetch data:

Here in this step, you will learn how to use service to fetch data. In the following code, I made a call to the JSONPlaceholder website which provides fake online REST API for testing and prototyping purposes. I created a function in service and made a call to fetch data.

Put the following code in userdata.service.ts file.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserdataService {

  constructor(private http: HttpClient) { }

  getUserData() {
    const url = 'https://jsonplaceholder.typicode.com/users';
    return this.http.get(url);
  }
}

Step 3: Using service into component to access data

I have used service into AppComponent to access data fetched by service. Then after accessing that data, I used for loop in HTML file to represent data. I have displayed name, username, email and phone respectively from the data.

Put the following code in app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { UserdataService } from './userdata.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  userData;
  constructor(private userDataService: UserdataService) { }

  ngOnInit() {
    this.userDataService.getUserData().subscribe((data) => {
      this.userData = data;
    });
  }
}

Step 4: Rendering the view

Put the following code in app.component.html file.

<div *ngIf="userData">
  <h1 class="center">User Data</h1>
  <div>
    <table>
      <tr>
        <th>Name</th>
        <th>Username</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
      <tr *ngFor="let data of userData">
        <td>{{data.name}}</td>
        <td>{{data.username}}</td>
        <td>{{data.email}}</td>
        <td>{{data.phone}}</td>
      </tr>
    </table>
  </div>
</div>

Put the following code in app.component.css file for styling purpose.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}
td, th {
  border: 1px solid black;
  padding: 5px;
}

.center {
  text-align: center;
}

Output:

Conclusion:

From this article, you learned the importance of services in angular and how to use them. If you any questions or feedback, you can mention it in the comment section.

See also:

Components in angular
template vs templateUrl
*ngFor in angular
CRUD Operations in Angular

Leave a Reply

Your email address will not be published. Required fields are marked *