Angular Services
Angular Services are reusable classes used to organize business logic, share data, perform API operations, and provide common functionality across components.
What is an Angular Service?
A service is a reusable TypeScript class that contains logic which can be shared by multiple Angular components.
Services help keep components simple by moving reusable logic, data operations, API calls, and other common functionality into separate classes.
Simple Definition
An Angular Service is a reusable class that provides functionality to one or more components.
Angular Service Flow
Why Use Angular Services?
Reusable Logic
Write functionality once and reuse it in multiple components.
Reusable Code
Share Data
Share application data between different components.
Shared Data
API Calls
Keep HTTP and API-related operations outside components.
HttpClient
Clean Components
Keep components focused on UI and user interaction.
Separation
Basic Service Structure
An Angular service is normally created as a TypeScript class and can be provided using Angular dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourseName(): string {
return 'Angular Full Stack';
}
}
Important
The @Injectable() decorator marks the class as available for Angular's dependency injection system.
Component Using a Service
A component can receive a service through its constructor and then use the service methods.
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
(click)="loadCourse()"
class="btn btn-primary">
Load Course
</button>
<p>
Course:
{{ courseName }}
</p>
Course: Angular Full Stack
What Can a Service Do?
Data Management
Store and manage application-related data.
getCourses()
API Communication
Communicate with backend APIs using HttpClient.
http.get()
Business Logic
Keep reusable calculations and application rules.
calculateFee()
Shared State
Share information between components when required.
BehaviorSubject
1. Reusable Service Example
The same service can be injected into different components, allowing the application to reuse the same logic.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
showMessage(message: string): void {
console.log(message);
}
}
constructor(
private notificationService: NotificationService
) {
}
showWelcome(): void {
this.notificationService.showMessage(
'Welcome to Angular'
);
}
How it works
The notification logic remains in the service, while the component simply calls the required service method.
2. Service for Course Data
A course service can centralize course-related data and allow multiple components to access the same information.
@Injectable({
providedIn: 'root'
})
export class CourseService {
private courses: string[] = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
getCourses(): string[] {
return this.courses;
}
}
courses: string[] = [];
constructor(
private courseService: CourseService
) {
}
ngOnInit(): void {
this.courses =
this.courseService.getCourses();
}
Available Courses
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
3. Service for API Communication
API communication is commonly placed inside a service rather than directly inside a component.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CourseService {
private apiUrl =
'https://api.example.com/courses';
constructor(
private http: HttpClient
) {
}
getCourses() {
return this.http.get(this.apiUrl);
}
}
ngOnInit(): void {
this.courseService
.getCourses()
.subscribe(data => {
this.courses = data;
});
}
4. Sharing Data Between Components
A service can maintain shared data so that multiple components can access the same information.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedCourseService {
selectedCourse = '';
setCourse(course: string): void {
this.selectedCourse = course;
}
getCourse(): string {
return this.selectedCourse;
}
}
Simple Idea
One component can update shared information through the service, while another component can read the same information from that service.
5. Service Scope
Angular services can be provided at different levels depending on how widely the service should be available.
| Provider | Scope | Purpose |
|---|---|---|
providedIn: 'root'
|
Application-wide | Shared service available throughout the application. |
| Component Provider | Component-level | Service instance associated with a component scope. |
| Module / Injector Scope | Specific application scope | Used when service availability needs to be restricted. |
6. Dependency Injection with Services
Angular's dependency injection system creates and provides service instances to components that request them.
constructor(
private courseService: CourseService
) {
}
Complete CIIT Training Institute Example
Suppose CIIT Training Institute has a course dashboard that needs to display available courses. Instead of keeping course data and related logic inside the component, we can place it in a service.
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;
}
getInstituteName(): string {
return 'CIIT Training Institute';
}
}
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
Component vs Service
| Component | Service |
|---|---|
| Mainly manages UI and user interaction. | Mainly manages reusable application logic. |
| Contains template-related behavior. | Can contain data and business logic. |
| Uses services when functionality is needed. | Can be injected into multiple components. |
| Should avoid unnecessary reusable logic. | Helps keep reusable logic centralized. |
Important Points About Angular Services
- Services are reusable TypeScript classes.
- Services help separate application logic from UI code.
- Services can be used for data management and API communication.
- Multiple components can use the same service.
- Angular dependency injection provides required services.
- Services can be used to share data between components.
Angular Service Best Practices
- Keep reusable logic inside services instead of duplicating it across components.
- Keep components focused mainly on presentation and interaction.
- Use meaningful service names such as CourseService or TrainingService.
- Keep API communication inside dedicated services.
- Avoid putting unrelated responsibilities into one large service.
- Use dependency injection instead of manually creating service instances.
Summary
Angular Services are reusable classes that help organize application logic, data operations, API communication, and shared functionality.
By using services with Angular dependency injection, applications become more reusable, maintainable, and easier to organize.