Introduction To Angular Service and Its Features

Want to get the complete information on Angular Services? As the name suggests, Angular Services are used to offer “services” to various components. These services could range from simple data entry to other complex functionalities. This article on Angular Services covers the following topics: 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What is the Need for Angular Services?

We’re sure you are aware of the concept of components in Angular. The user interface of the application is developed by embedding several components into the main component. 

Angular_Components

However, these components are generally used only for rendering purposes. They are only used to define what appears on the user interface. Ideally, other tasks, like data and image fetching, network connections, database management, are not performed. Then how are these tasks achieved? And what if more than one component performs similar tasks? Well, Services take care of this. They perform all the operational tasks for the components. 

  • Services avoid rewriting of code. A service can be written once and injected into all the components that use that service
  • A service could be a function, variable, or feature that an application needs

What Are Angular Services?

Angular services are objects that get instantiated just once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e., data is available all the time. 

Angular_Services

The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application. They are usually implemented through dependency injection. 

Features of Angular Services

  • Services in Angular are simply typescript classes with the @injectible decorator. This decorator tells angular that the class is a service and can be injected into components that need that service. They can also inject other services as dependencies. 
  • As mentioned earlier, these services are used to share a single piece of code across multiple components. These services are used to hold business logic. 
  • Services are used to interact with the backend. For example, if you wish to make AJAX calls, you can have the methods to those calls in the service and use it as a dependency in files.

Features-Angular_Services

  • In angular, the components are singletons, meaning that only one instance of a service that gets created, and the same instance is used by every building block in the application. 
  • A service can be registered as a part of the module, or as a part of the component. To register it as a part of the component, you’ll have to specify it in the providers’ array of the module.

Now that you know what services in Angular are, let us help you understand its working with the help of a simple demo. 

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Demo - Using Services to Display Employee Database

Use Case:

  • Create employee details such as name, employee ID, and email ID.
  • Click on the employee button to retrieve an employee’s data
  • Add the location for the employees in the list

Step 1: Create a component to display the employee records. Use the command

ng g c <component name> for the same. We’ve created the component, e-info.

Step 2: Create a service using the command, ng g service <service name>. We’ve created a service called data. Once run, two files data.service.ts and data.service.spen.ts are created. The service consists of the employee data that needs to be displayed. We are making use of three arrays for the same. 

info1: string[]=["John Mathew",'E354','jm@abc.net']

info2: string[]=["Rob Wilson",'E673','rw@abc.net']

info3: string[]=["Rose Adams",'E865','ra@abc.net']

In order to retrieve this data in our component, we make use of a method. This method returns the employee data. 

getInfo1():string[]{

    return this.info1

  }

  getInfo2():string[]{

    return this.info2

  }

  getInfo3():string[]{

    return this.info3

  }

Step 3: In order to retrieve this information, in the e-info.component.ts file, we need to create three more arrays and methods. 

infoReceived1: string[]=[];

  infoReceived2: string[]=[];

  infoReceived3: string[]=[];

  getInfoFromService1(){

    this.infoReceived1 = this.dservice.getInfo1()

  }

  getInfoFromService2(){

    this.infoReceived2 = this.dservice.getInfo2()

  }

  getInfoFromService3(){

    this.infoReceived3 = this.dservice.getInfo3()

  }

Now you must be wondering how this works. As mentioned, services are implemented using dependency injection. The service class is imported into the component.ts file. The main reason for doing this is to tell Angular that when the component is created, an instance of the service class is also created to perform all the tasks. The instance should also be declared in the providers’ array of the component. However, to access this instance, an object is created that can access the methods and variables of the service class. We’ve created the object dservice for the same.

import { Component, OnInit } from '@angular/core';

import { DataService } from "../data.service"

@Component({

  selector: 'app-e-info',

  templateUrl: './e-info.component.html',

  styleUrls: ['./e-info.component.css'],

  providers: [DataService]

})

export class EInfoComponent implements OnInit {

  infoReceived1: string[]=[];

  infoReceived2: string[]=[];

  infoReceived3: string[]=[]; 

  getInfoFromService1(){

    this.infoReceived1 = this.dservice.getInfo1()

  }

  getInfoFromService2(){

    this.infoReceived2 = this.dservice.getInfo2()

  }

  getInfoFromService3(){

    this.infoReceived3 = this.dservice.getInfo3()

  }

constructor(private dservice: DataService) { }

  ngOnInit(): void {

  }}

We have also highlighted the code for better understanding. 

Dive Deep Into Java Core Concepts

Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

Now that you know the logic behind what is being displayed and how it’s being displayed, let’s move on to the UI of the application. 

Step 4: In the component.html file, we are creating an unordered list. We’ve made use of the *ngfor directive to loop over the records and display the information. 

<button type="button" name="button" (click)='getInfoFromService1()'>Employee1</button>

<ul class="list-group">

    <li *ngFor = "let info of infoReceived1" class="list-group-info">{{info}}</li>

</ul>

<button type="button" name="button" (click)='getInfoFromService2()'>Employee2</button>

<ul class="list-group">

    <li *ngFor = "let info of infoReceived2" class="list-group-info">{{info}}</li>

</ul>

<button type="button" name="button" (click)='getInfoFromService3()'>Employee3</button>

<ul class="list-group">

    <li *ngFor = "let info of infoReceived3" class="list-group-info">{{info}}</li>

</ul>

A bootstrap class of “list-group-info” is created to interpolate “info” which displays the contents of the info variable. In order to call the methods in the .ts file, we bind them with the button. Since it is bound with the click event, it is called when the button is clicked. 

Step 5: Create the custom HTML tag with the component selector in the main components, i.e., app.component.html

<img src= "assets/Logo.png" class="center" width="200" height="80" display:block>

<h1>Angular Services</h1> 

<app-e-info></app-e-info>

Here, we have added additional code only for the purpose of beautifying the user interface. You can ignore it if you like. 

Once you run your application, the browser will look like this: 

Services_Angular

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Step 6: The last part of the use case was to add the location to the employee records. The location is given by the user, as a result of which, we are making use of a form with an input field. 

Services are used to make such modifications. Data can be updated, altered, or deleted easily. They prove to be extremely flexible in this regard. 

<form #frm = "ngForm" (ngSubmit)="updateInfo(frm)">

    <div class="">

        <input type="text" name="location" value="" ngModel>

        <button type="submit" name="button">Add Info</button>

    </div>

</form> 

We highly suggest that you go through the article on Angular forms or watch our video on the same. The template variable frm is created to access all the values within the form. Since forms are being used, go ahead and import the module in your app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { EInfoComponent } from './e-info/e-info.component';

@NgModule({

  declarations: [

    AppComponent,

    EInfoComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    FormsModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Step7: Create the method “updateInfo()” in the component.ts file which takes the variable frm as a parameter. This method when called updates the employee records.

updateInfo(frm: any){

    this.dservice.addInfo(frm.value.location)

  }

However, the information (input location) should be appended to the info arrays created in the service. The addInfo() method in the service.ts file does the job.

addInfo(info){

    this.info1.push(info)

    this.info2.push(info)

    this.info3.push(info)

    return this.info1

  }

Step 8: Now, save your file and execute it. The output should look something like this 

Output_Services

So, this concludes the demo on Angular services. We recommend you play around with it to get a better understanding of the concept.

Take the Leap and Master Java Development

Java Certification TrainingENROLL NOW
Take the Leap and Master Java Development

Next Steps

We hope that this article on Angular Services helped you understand how to inject services into components and how a single piece of code can be used by multiple components. If you are looking to get advanced practical learning of Angular and perhaps make a career out of it, certification will come in handy.

Simplilearn's Full Stack Java Developer gives you an in-depth understanding of front-end web development with Angular. As part of this course, you will learn to create applications including facilitating development of single-page web applications, components, dependency injection, typescript. The course also includes a real-time project to test your skills and help you perfect them. 

If you have feedback or questions on the topic, feel free to drop us a comment in the comments section of this article. We will get back to you ASAP! 

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.