Angular Services

 

What is an Angular Service?

Service is a piece of reusable code with a focused purpose. A code that you will use in many components across your application

Our components need to access the data. You can write data access code in each component, but that is very inefficient and breaks the rule of single responsibility. The Component must focus on presenting data to the user. The task of getting data from the back-end server must be delegated to some other class. We call such a class a Service class. Because it provides the service of providing data to every component that needs it.

What Angular Services are used for

  1. Features that are independent of components such a logging services
  2. Share logic or data across components
  3. Encapsulate external interactions like data access

Advantages of Angular Service

  1. Services are easier to test.
  2. They are easier to Debug.
  3. We can reuse the service at many places.

How to create a Service in Angular?

An Angular service is simply a Javascript function. All we need to do is to create a class and add methods & properties. We can then create an instance of this class in our component and call its methods.

Step 1

Create a new file under the folder src/app and call it User.ts

export interface User {
    id: number,
    name: string,
    email: string,
    mobile: string,
    gender: string,
    dob: Date,
    isActive: boolean,
    range?: any,
    userType?: string,
    rating:number
}

Step 2

Next, let us build an Angular Service, which returns the list of users.

Create a new file under the folder src/app and call it user.service.ts with the help of Angular CLI. Type the below mentioned command and this command will generate the service for us.

ng g s service/user
import { Injectable } from '@angular/core';
import { User } from '../User';

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

Step 3

Now add the below mentioned methods to perform CRUD operation

import { Injectable } from '@angular/core';
import { User } from '../User';

@Injectable({
  providedIn: 'root'
})
export class UserService {
    private userList: User[] = [{
        id: 1,
        name: 'Ankush Agnihotri',
        dob: new Date('08/31/1992'),
        email: '[email protected]',
        gender: 'Male',
        mobile: '9041627385',
        isActive: true,
        range: [0, 10],
        rating:4,
        userType: 'Admin'
    }];
    constructor() {}
    getUsers() {
        return this.userList
    }
    getUsersByID(id: number) {
        return this.userList.find(x => x.id == id)
    }
    addUser(user: User) {
        user.id = new Date().getTime();
        this.userList.push(user);
    }
    updateUser(user: User) {
        const userIndex = this.userList.findIndex(x => x.id == user.id);
        if (userIndex != null && userIndex != undefined) {
            this.userList[userIndex] = user;
        }
    }
    removeUser(id: number) {
        this.userList = this.userList.filter(x => x.id != id);
    }
}

Invoking the UserService

We start with importing User model UserService in userlist component

We create an instance of UserSerivce in the constructor of the UserListComponet

The getUsers method calls the getUsers method of the UserService. It returns a list of Users, which we store in the local variable userList

import { Component, OnInit } from '@angular/core';
import { UserService } from '../service/user.service';
import { User } from '../User';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
  userList: User[] = [];
  constructor(private userService: UserService) {}
  ngOnInit(): void {
  }
  getUsers() {
   // Get Users from UserService
   this.userList = this.userService.getUsers();
  }
}

Template

The next step is to display the User list in table

Open the userlist.component.html file and write code for it

<div class="container">
    <h1 class="heading"><strong>Services </strong>Demo</h1>
    <button type="button" (click)="getUsers()">Get Users</button>
     <div class='table-responsive'>
            <table class='table'>
                <thead>
                    <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Mobile</th>
                <th>DOB</th>
                <th>isActive</th>
                <th>Action</th>
            </tr>
                </thead>
                <tbody> 
                   <tr *ngFor="let user of userList;">
                     <td>{{user.name}}</td>
                     <td>{{user.email}}</td>
                     <td>{{user.mobile}}</td>
                     <td>{{user.dob | date:'d/M/yyyy'}}</td>
                     <td>{{user.isActive}}</td> 
                  </tr>
                </tbody>
            </table>
        </div>
</div>


Similar Articles