In this article, we will talk about another core feature of building Single Page Applications (SPAs) with Angular i.e. services. Modern front-end frameworks/libraries operate on the primary concept of component-based development. In a practical setting, the component itself cannot provide a fully functional application experience unless it is not provided with the relevant data to perform dynamic operations on. 

Hence, Angular provides a concept of services via which we can supply relevant data to the components in order to have a smooth application experience. The combination of components and services in a SPA contributes to better code management, maintenance, and scalability. 

Throughout this article, we will see how Angular creates these services and enables their utilization in the overall application. Towards the end, we’ll have a brief look at the default boilerplate code which Angular generates when we create a new service. Without further ado, let’s start!

What is Angular?

Angular is one of the most popular frameworks for building web applications. Due to its ease and contribution towards component-based development, it is widely used for building Single Page Applications (SPAs). If you’re not familiar with component-based development, let me explain it to you briefly! Think of your browser screen as divisions; header, footer, side menu, main area, etc. Even inside the main area, you might have multiple sub-parts that function differently according to the application use case. We refer to these parts and sub-parts as components in Angular.

Ideally, these components are independent and reusable. If we wish to dynamically change a single part of a web page, there is no need to reload the entire page. Instead, using the component-based approach, we can only reload the specific part/component. Hence, contributing to better user experience. 

This was a brief recalling introduction of Angular and I hope by now you’re ready to learn and explore services in Angular.

What are Services in Angular?

As we briefly discussed in the introduction, services are extremely vital entities inside the Angular application architecture. They contain methods that deal with all the incoming and outgoing data flows and enable the application to entail fresh runtime executions. On top of data management, services are also responsible to refactor/process the incoming and outgoing data according to the requirements and encapsulate the business logic as well. 

Services are strongly in touch with Angular components. There is two-way communication between services and components. The data, which service(s) have, is passed to the relevant component(s) for rendering purposes. On the other hand, the data which component(s) generate, via user dynamic inputs, is passed to the relevant service(s) for multiple business operations.

The question here is that where does the data come from? Generally, these services obtain data via API calls. Once the data is retrieved in the service, we can perform its manipulation and processing (if required) within the service. After all these steps, we pass this data to the relevant component(s) for rendering and other purposes.

Angular services do not exist stand-alone. In order to create and utilize them, we first need to initiate an Angular project. We can create a new Angular project learning-angular by running the following command in the console window.

ng new learning-angular

If you face any issues while creating the project, you can see our detailed guide on creating an Angular project here.

Creating Services

We use ng generate service <your_service_name> to create a new service in Angular. Let’s create a new service my-first-service for our project. Navigate to the project directory and run the following command.

ng generate service my-first-service/my-first-service

The above command will create a service my-first-service in ./src/app/ as shown below.

Navigate into my-first-service folder. You’ll see two .ts files as shown below.

Understanding the Service File Structure

You might be wondering what are these files for. Don’t worry! Just hang on a bit. We will explore these files in great detail very shortly. For now, just note that my-first-service.service.ts is the actual file in which we will write the code for service. The other file, my-first-service.service.spec.ts, is for the purpose of unit testing of this service. If you’re not familiar with unit testing then don’t worry. As a beginner, you don’t need to get overwhelmed by writing unit tests for your services. If you wish to know about unit testing, you may read about them in great detail here.

The latter portion of this section will explain to you the default boilerplate code which Angular generates inside the service file. Let’s start!

1. my-first-service.service.ts

In the my-first-service.service.ts file, we can see the following piece of default code.

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

Angular service is a class itself. The only difference is that the class is decorated by Injectable decorator which allows the service to be provided and injected as a dependency.

On line 1, we are importing the Injectable decorator from @angular/core module. On line 5, we are actually declaring the class which will act as a service in our application. Note that there is an export keyword before the class declaration. This keyword allows the global usage of this class (as a component) in the entire application which means that we can import this component in any file throughout the application. If we don’t export it, we will not be able to import it in any other file.

From lines 3 to 5, we are decorating the class with Injectable decorator so that we can inject this service as a dependency on components as well as other services. The providedIn: 'root’ inside the decorator makes sure that this is the application-level injector and the current service will have only one instance throughout the application. The same instance will be injected into every component/module which requires this service.

Wrapping Up

This was the overall synopsis of creating services in Angular. In this article, we learned to create services and understood the default boilerplate code inside the service file. I hope after reading this article, you have some idea about services in Angular. 

Feel free to write in the comment section in case of any confusion or queries. If you wish to learn more about Angular, you can check out our collection of Angular tutorials.