Services in Angular: Services and Dependency Injection

Read it in 12 Mins

Published
29th Sep, 2022
Views
7,768
The Only Way to Learn Coding

Is by Doing

Video Thumbnail Image
Services in Angular: Services and Dependency Injection

What are services in an Angular app?

Services is a general term broadly categorized as values, functions, or features that our application may need. Services are made to reuse codes designed for a purpose.

Angular services differentiate an element from its service so that the services can be re-used. This increases the modularity of the Angular application. Service in an Angular App can be almost anything, it can be an element, a component, or it can be a module used for some specific purpose.

All services in Angular App are classes with a definite purpose. It serves a purpose and serves it well.

Some of the very well-known services include:

  • Logging Service: Used for logging in, logging out.
  • Data Fetching: Fetching Data and representing it in a formatted way.
  • Data Service: Fetching and receiving Data.
  • Message Bus: Used for communicating through a set of shared interfaces.
  • Tax Calculator: Calculating Tax by synchronizing with the current Law system.
  • EMI calculator: Easy Monthly Instalment Calculator, mainly used in calculations related to Loan. 
  • Application Configuration: Common configuration throughout the application support.

Here is an article on angular cli.

Reusability

Reusability is very important when building large-scale applications. Classes built for a common purpose should not be required to be built again and again. This even causes misinterpretation of certain important classes. We need to implement separation of concerns to segregate different classes used for different purposes. This can be achieved by Angular services.

In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module.

All the Angular Services contain many methods that maintain data throughout the lifetime of an application. Thus, it has become a medium to share various responsibilities within one or multiple components.

Services and Dependency Injection

Services provide us with injectable features. The Angular App provides us the decorator @Injectable for creating a service. Classes thereby created can be injected into any other module or component by calling it through service provider modules.

The two-step process for creating a service in Angular application is:

  1. Use @Injectable decorator to create a class.
  2. Use Dependency Injection to inject the class or register the class with the service provider.

In Angular 13 Framework, one of the ways of performing DI – Dependency Injection is by using Service injection. Dependencies are services or objects of a class that helps in performing its function. Dependency injection or DI are design patterns in which a class demands dependencies from external sources rather than constructing them.

Building and providing services

Let us build a service for keeping Records of Employees:

Step 1: Install Node.js:

Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.

The latest Version is : node-v16.13.1-x64

Install node.js once downloaded:

Angular: Add service to module Code Example

Angular: Add service to module Code Example

Once you have installed Node.js on your system, open node.js command prompt.

To check your version, run node -v in a terminal/console window.

Angular: Add service to module Code Example

Step 2: Use npm to Install Angular CLI

Use the following command to install Angular CLI

npm install -g @angular/cli 

Or

npm install -g @angular/cli@latest

Angular: Add service to module Code Example

Or

Just go to Angular CLI official website https://cli.angular.io/

You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are same for Windows and Mac.

Angular: Add service to module Code Example

To check Node and Angular CLI version, use ng --version command.

Angular: Add service to module Code Example

Step 3: Create an app called ngApp4Service

Syntax:

ng new app_name

C:\>ng new ngApp4Service 

It asks for

Would you like to add Angular routing? Yes

Which stylesheet format would you like to use?

> CSS

….

Angular: Add service to module Code Example

Angular: Add service to module Code Example

Step 4: Generate Service via CLI:

Syntax for creating a service:

ng generate service <name> [options]

ng g service <name> [options]

Let us generate the required service: here we are going to create “Employee” Service.

Go to the app folder and install the required service: “Employee”:

Angular: Add service to module Code Example

Step 5: Edit the service ts file:

Service to store Employee Data: employee.service.ts

File name: employee.service.ts

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {

public _empList: Array<any> = [];  
    constructor() {  
        this._empList = [{name:'Jay Choudhury', city:'Ghaziabad'}];  
    }  
     returnEmpData(): Array<any> {  
        return this._empList;  
    }  
     addEmpData(item: any): void {  
        this._empList.push(item);  
    }  
}

Step 6: Import the employee service:

Import the service in the app.module.ts:

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
import { AppComponent } from './app.component';  
import { EmployeeService } from './employee.service';  
@NgModule({  
  declarations: [  
    AppComponent  
  ],  
  imports: [  
    BrowserModule, FormsModule, ReactiveFormsModule  
  ],  
  providers: [EmployeeService],  
  bootstrap: [AppComponent],  
  schemas: [NO_ERRORS_SCHEMA]  
})  
export class AppModule { }

Step 7: Use the service: Employee:

Edit: app.component.ts

import { Component, OnInit } from '@angular/core';  
import { EmployeeService } from './employee.service';  
@Component({    
  selector: 'app-root',  
      templateUrl: './app.component.html',  
      styleUrls : ['./app.component.css']  
      })  
export class AppComponent implements OnInit {  
      public model: any = {};  
      public source: Array<any>;  
      constructor(public service: EmployeeService) {  
            this.source = this.service.returnEmpData();  
            }  
       ngOnInit(): void { }  
       public submit(): void {  
            if (this.validate()) {  
                this.service.addEmpData(this.model);  
                this.reset();  
            }  
        }  
      public reset(): void {  
       this.model = {};  
   }  
       public validate(): boolean {  
               let status: boolean = true;  
               if (typeof (this.model.name) === "undefined") {  
                      alert('Name is Blank');  
                      status = false;  
                      return status;        
               }  
               else if (typeof (this.model.city) === "undefined") {  
                      alert('City is Blank');  
                      status = false;  
                      return status;        
               }  
               return status;  
        }  
 }

Edit app.component.html:

<div>    
    <h2>Employee Form</h2>   <table border="1">  
     <tr>   <td>Employee Name</td>    
        <td><input type="text" [(ngModel)]="model.name" /></td>  </tr>  
     <tr> <td>City</td>    
         <td><input type="text" [(ngModel)]="model.city" /></td>  </tr>  
     <tr> <td></td> <td><input type="button" value="Submit" (click)="submit()" />      
      <input type="button" value="Reset" (click)="reset()" /></td></tr> </table>  
    <h3>Employee Details</h3>  
    <div><div>
        <div>  
         <table border="1">  
            <thead><tr><th> <span>Employee's Name</span> </th>
                   <th> <span>City</span></th></tr></thead>
            <tbody> <tr *ngFor="let item of source; let i=index">  
                    <td><span>{{item.name}}</span></td>    
                    <td><span>{{item.city}}</span></td>  </tr>  
           </tbody>  </table>  </div>  
       </div>
    </div>  
</div>

Step 8: Run to check the service:

Go to the app folder:

C:\>ng serve

Angular: Add service to module Code Example

Run at localhost:4200/

We get the Employee Form.

We can add more details for the employee, and see the result.

Angular: Add service to module Code Example

Angular: Add service to module Code Example

Importance of Services

Angular App provides Angular Services as re-usable components of the application. It uses @Injectable Decorator for building a Service. A service can be called through multiple components as a common element and shared for various purposes. This helps in avoiding repetitive work and improves the speed of app development.

Profile

Monica Gupta

Author

I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

Share This Article
Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)

Upcoming Web Development Batches & Dates

NameDateFeeKnow more