Creating Angular Services
Angular services are reusable TypeScript classes that can be created to organize application logic, manage data, communicate with APIs, and provide common functionality to components.
What Does Creating a Service Mean?
Creating an Angular service means defining a reusable TypeScript class and registering it with Angular's dependency injection system.
Once created, the service can be injected into components and other Angular classes wherever its functionality is required.
Simple Definition
A service is a reusable class that contains functionality which can be shared across different parts of an Angular application.
Service Creation Flow
1. Create a Service Using Angular CLI
Angular CLI provides a command for generating a service quickly inside an Angular project.
ng generate service course
The shorter version of the same command is:
ng g service course
Result
Angular CLI creates the service file and prepares the class for dependency injection.
2. Files Generated by CLI
When a service is generated, Angular CLI normally creates a TypeScript service file.
src/
└── app/
└── course.service.ts
course.service.ts
Contains the service class and its methods.
Service Class
TypeScript
Service logic is written in TypeScript.
class
Injectable
Angular can provide the service through dependency injection.
@Injectable()
Reusable
The service can be used by multiple components.
Reuse
3. Basic Service Structure
A basic Angular service contains the @Injectable() decorator and a TypeScript class.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
}
What is @Injectable?
The @Injectable() decorator tells Angular that the class can participate in dependency injection.
4. Adding Methods to a Service
After creating a service, reusable methods can be added to provide functionality to components.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourseName(): string {
return 'Angular Full Stack';
}
getDuration(): string {
return '5 Months';
}
}
Course: Angular Full Stack
Duration: 5 Months
5. Using the Created Service in a Component
After creating a service, it can be injected into a component through the constructor.
import { Component } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course',
templateUrl: './course.component.html'
})
export class CourseComponent {
courseName = '';
constructor(
private courseService: CourseService
) {
}
loadCourse(): void {
this.courseName =
this.courseService.getCourseName();
}
}
<button
class="btn btn-primary"
(click)="loadCourse()">
Load Course
</button>
<p>
Course:
{{ courseName }}
</p>
Course: Angular Full Stack
6. Creating a Service with Data
A service can store application data and expose methods for accessing that data.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TrainingService {
private courses: string[] = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
getCourses(): string[] {
return this.courses;
}
}
Why Keep Data in the Service?
Multiple components can use the same service method instead of storing duplicate course data in every component.
7. Useful Service Creation Commands
| Command | Purpose |
|---|---|
ng generate service course
|
Creates a service named CourseService. |
ng g service course
|
Short form of the generate service command. |
ng generate service services/course
|
Creates a service inside a services folder. |
8. Organizing Services in a Project
In a larger Angular application, services can be organized inside a dedicated folder.
src/
└── app/
├── components/
├── services/
│ ├── course.service.ts
│ ├── training.service.ts
│ └── notification.service.ts
└── app.component.ts
Benefit
Keeping related services organized makes the project easier to navigate and maintain.
9. providedIn: 'root'
A commonly used service configuration is providedIn: 'root'.
@Injectable({
providedIn: 'root'
})
export class TrainingService {
getInstituteName(): string {
return 'CIIT Training Institute';
}
}
Complete CIIT Training Institute Example
Let's create a service for CIIT Training Institute that provides the institute name and available courses.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TrainingService {
private courses: string[] = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
getInstituteName(): string {
return 'CIIT Training Institute';
}
getCourses(): string[] {
return this.courses;
}
}
import { Component, OnInit } from '@angular/core';
import { TrainingService } from './training.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {
instituteName = '';
courses: string[] = [];
constructor(
private trainingService: TrainingService
) {
}
ngOnInit(): void {
this.instituteName =
this.trainingService.getInstituteName();
this.courses =
this.trainingService.getCourses();
}
}
<h2>
{{ instituteName }}
</h2>
<h4>
Available Courses
</h4>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
CIIT Training Institute
Available Courses
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
Service Creation Checklist
- Generate the service using Angular CLI.
- Create meaningful methods inside the service.
- Use @Injectable() for dependency injection.
- Use providedIn: 'root' when an application-wide service is appropriate.
- Inject the service into components that need it.
- Keep reusable logic inside services instead of duplicating it across components.
Creating Services Best Practices
- Use descriptive service names such as CourseService or TrainingService.
- Keep one service focused on a related responsibility.
- Keep API communication and reusable data logic inside services.
- Avoid placing unnecessary UI logic inside services.
- Organize services into folders in larger projects.
- Use dependency injection instead of manually creating service instances.
Summary
Angular services can be created using the Angular CLI and implemented as reusable TypeScript classes with the @Injectable() decorator.
After creation, services can expose methods and data that components can access through Angular's dependency injection system.